Php – apache2: Require valid-user AND allow all

apache-2.2denyhttp-basic-authenticationPHP

I want to allow basic authentication, but not require it. All visitors -authenticated or not- should be able to acces a page (script) where the script can add special features for valid users.
So first try the basic authentication, if that fails, allow access anyway. The script will decide what to do next. I'd rather not do the whole authentication inside the script but let apache do the authentication and just pass the username (if any) to the script.

I'm actually creating a SOAP-service, not a website, but you might imagine a situation where you can visit the homepage of a site without being prompted for a username/password and then visit a members-only page which triggers the http-authentication. Revisiting the homepage can now result in a personalised homepage.

I've been fidling with the .htaccess file and got this far:

AuthType Basic
AuthName "Beveiligde website"
AuthUserFile .htpasswd
require valid-user
Order allow,deny
Allow from All
satisfy any

This does allow all, but unfortunately doen't first try the authentication (al least not as far a I can see.)
The environment variable AUTH_TYPE in PHP is empty, even when valid credentials are used.

Is it even possible to combine these this way? I could imagine apache only trying the basic authentication when the allow/deny rules result in a denial. Is there a way to force basic authentication anyway? or am I going at this in the wrong way altogether?

Best Answer

You'll need to be tricky :) To make the server ask for authentication you'll need to require a valid user. But that could go inside a Location block. So I'm thinking, you could then alias (or redirect) that location to the normal location. I think something like this will work:

<location "/try-auth-first">
require valid-user
satisfy all

alias /try-auth-first /the-real-one
#redirect /try-auth-first /the/real/one
</location>

You might need to fiddle a bit, but something like that should work. If the authentication fails, your script can pick up the 401 result and then retry directly to the real location (which needs to be set to allow from all).