ThSchrad
ThSchrad

Reputation: 35

Check permissions on every page request, then redirect

I wrote a web application on an apache (2.4) web server where users are authenticated via kerberos. I have a user table in my database with basic permissions (r, w) set to 0 or 1. Now I would like to check these permissions every time the user tries to access a page on this web server. When the user has no read permission he should be redirected to the page "forbidden.html". Obviously, apache can't do the permissions check. So I tried it with php.

What I have so far

I've put all html files in a subfolder /html in the apache DocumentRoot and put this into my configuration file to call php/auth.php every time the user requests a page in /html:

<Location /html>
    <If "%{REQUEST_URI} !~ m#\/forbidden\.html#">
            # Script checks if user should get access to the site
            SetHandler auth-script
            Action auth-script "/php/auth.php"
    </If>
</Location>

php/auth.php:

if ($params["user"]["r"] == 1) {
    // User has permission, redirect to the requested page
    header("Location: https://webapp.domain.de".$_SERVER["REQUEST_URI"]);
} else {
    // User has no permission, redirect to forbidden.html
    header("Location: https://webapp.domain.de/html/forbidden.html");
}

Problem

My problem is that I get a redirect loop. It seems the redirect from auth.php's header() again triggers the auth.php script through apache's Action directive. This behaviour does not appear when the user is redirected to forbidden.html because it is excluded in the conf file.

I tried commenting out the header() in auth.php, but apache will not serve the requested site automatically with the Action directive.

Is there a way to know if auth.php already redirected the user in this request and tell apache to not call the script. Or is there an even better way to do what I want to achieve?

Thanks in advance.

Upvotes: 1

Views: 770

Answers (1)

Nic3500
Nic3500

Reputation: 8621

I did something similar without using Apache directives at all (hosted site, can't change anything). You do not need the Apache redirection part.

In every phtml file, the first action I do is to require a PHP page similar to your auth.php. If auth.php detects that the user does not have the rights for the page, I send back a header to redirect him, like so:

header('Location: http://www.example.com/forbidden.html');

Just make sure that nothing else is printed before the call to header, and non-authorized users will end up in your Location page.

If the user is authorized, no header, no redirection, keep going "down" the page.

Upvotes: 1

Related Questions