3.4 Now something More Complicated - Authentication

Now that you know how to write a primitive handler, let's try something more complicated.

Let's say we want to password-protect this directory. We want the login to be "spam", and the password to be "eggs".

First, we need to tell Apache to call our authentication handler when authentication is needed. We do this by adding the PythonAuthenHandler. So now our config looks like this:

  <Directory /mywebdir>
      AddHandler mod_python .py
      PythonHandler myscript
      PythonAuthenHandler myscript
      PythonDebug On
  </Directory>

Notice that the same script is specified for two different handlers. This is fine, because if you remember, mod_python will look for different functions within that script for the different handlers.

Next, we need to tell Apache that we are using Basic HTTP authentication, and only valid users are allowed (this is fairly basic Apache stuff, so we're not going to go into details here). Our config looks like this now:

  <Directory /mywebdir>
     AddHandler mod_python .py
     PythonHandler myscript
     PythonAuthenHandler myscript
     PythonDebug On
     AuthType Basic
     AuthName "Restricted Area"
     require valid-user
  </Directory>

Now we need to write an authentication handler function in myscript.py. A basic authentication handler would look like this:

from mod_python import apache

def authenhandler(req):

    pw = req.get_basic_auth_pw()
    user = req.user

    if user == "spam" and pw == "eggs":
       return apache.OK
    else:
       return apache.HTTP_UNAUTHORIZED

Let's look at this line by line: