making HTTP authentication optional with mod-python
-
16-09-2019 - |
Question
I've a web application that accesses multiple controller classes based on the parameters it is passed. For some of the controllers, I want users to authenticate themselves (by simple HTTP authentication), and for some I want public access.
Is there a way to make this happen? In my .htaccess file, I now have
AddHandler mod_python .py
PythonHandler handler
PythonAuthenHandler handler
PythonDebug On
AuthType Basic
AuthName "My Realm"
AuthBasicAuthoritative Off
require valid-user
The authenhandler is called correctly, but even when I just do
def authenhandler(req):
return apache.OK
the user is asked for a password (though any password that is entered is accepted)
I tried removing the Auth* stuff (and the require directive) from the .htaccess entirely, and just did the following in the normal handler for those cases where I do want authentication (and it was not found):
request.err_headers_out.add('WWW-Authenticate', 'Basic realm="My Realm")
return apache.HTTP_UNAUTHORIZED
which is what I understand what the server should do when not receiving correct authentication. That did not work either, however.
I come from a PHP background and I know that the latter is how it's done in PHP - but PHP sometimes does extra little pieces of undocumented magic to make this stuff actually work. Is this one of those cases?
Is there any way to optionally request authentication, depending on the URL passed, from the same handler?
Solution
There are a couple ways to specify authentication scope with Apache, the one most people are used to is gt;Directorylt; based - i.e. anything in or below a directory gets authenticated against htpasswd.
There's also gt;Locationlt;, which applies directives to content that live outside the filesystem such as mod_python registered code.
This is how you can set authentication on a 'virtual' path like /status, if you have mod_status enabled.
You can do the same thing with mod_python paths
<Location /python/app1/>
Order allow,deny
Allow from all
</Location>
<Location /python/app2/>
Order allow,deny
Allow from all
AuthType basic
AuthName "Protected Intranet Area"
AuthUserFile /etc/apache2/htpasswd
Require valid-user
</Location>
I should add - it's not necessarily clear if you mean 'some users should authenticate with a username and password and other users should only have to put in a username'
or
'some applications should require authentication 100% of the time, and other applications should be freely available 100% of the time'
My first answer sorts out the last query.