PHP and .htaccess authentication solution

.htaccess, apache, php

Solution

You can use the `SetEnvIf` variable in the .htaccess file to check if a certain Cookie value is set. For example (this isn't very secure, but just for illustration):

AuthType Basic
AuthName "Protected Login"
AuthUserFile "/path/to/.htpasswd"
AuthGroupFile "/dev/null"
SetEnvIf Cookie PHPSESSID=.* PASS=1
Order deny,allow
Deny from all
Allow from env=PASS
Require valid-user
Satisfy any

The line `SetEnvIf Cookie PHPSESSID=.* PASS=1` checks if a Cookie is set with a PHP session id and if so, that is enough to `Satisfy` the authentication process and the `Allow from env=PASS` makes it skip the login prompt if this is true.

Again, this example is not very safe as a PHP session cookie is already set when `session_start()` is called without a succesful authentication attempt, so it would be better to set a more cryptical/random cookie value that's hard to guess. For example:

SetEnvIf Cookie AJNC3Z921dmc4O8P2 PASS=1

That way, if you set a cookie value of `AJNC3Z921dmc4O8P2` upon succesful authentication through PHP, this will be enough to pass the authentication process. Make sure to set a proper cookie expiration time though to avoid people from being able to pass the login prompt for a prolonged period.

Problem

Here's the layout: ``` web root - admin (dir) - index.php - js - img - other files / dirs - dir - files ``` Until now, I protected the admin dir with .htaccess passwd because I want full access control for all files in that dir (including js scripts, jpg, pdf etc). On the other hand, my custom CMS provides authentication using PHP sesssion / cookie for other URLs. What I want to accomplish is to use the same PHP authentication for the .htaccess protected dir, avoiding the popup prompt for user / password for already PHP authenticated users. In summary: - I want the admin dir to use the .htaccess rules for authentication - If a user is already authenticated using PHP (login in a HTML form, on a non-protected file), bypass the second .htaccess authentication process when accessing the admin dir content - If a non PHP authenticated user tries to access content in the admin dir, the HTTP auth popup should be triggered Most of the stuff that I've read suggest to move the admin dir outside the web root and access the files from a PHP script with readfile, which I don't want to do. There's dynamic content on that dir, as well as static. I know that apache will trigger the auth popup before loading any resources so the question is how to make apache aware that the user is already authenticated. Any other suggestion / workaround?

Original source