The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Apache::AuthCookie - Perl Authentication and Authorization via cookies

SYNOPSIS

Make sure your mod_perl is at least 1.24, with StackedHandlers, MethodHandlers, Authen, and Authz compiled in.

 # In httpd.conf or .htaccess:
 PerlModule Sample::AuthCookieHandler
 PerlSetVar WhatEverPath /
 PerlSetVar WhatEverLoginScript /login.pl
 
 # The following line is optional - it allows you to set the domain
 # scope of your cookie.  Default is the current domain.
 PerlSetVar WhatEverDomain .yourdomain.com

 # Use this to only send over a secure connection
 PerlSetVar WhatEverSecure 1

 # Usually documents are uncached - turn off here
 PerlSetVar WhatEverCache 1

 # These documents require user to be logged in.
 <Location /protected>
  AuthType Sample::AuthCookieHandler
  AuthName WhatEver
  PerlAuthenHandler Sample::AuthCookieHandler->authenticate
  PerlAuthzHandler Sample::AuthCookieHandler->authorize
  require valid-user
 </Location>

 # These documents don't require logging in, but allow it.
 <FilesMatch "\.ok$">
  AuthType Sample::AuthCookieHandler
  AuthName WhatEver
  PerlFixupHandler Sample::AuthCookieHandler->recognize_user
 </FilesMatch>

 # This is the action of the login.pl script above.
 <Files LOGIN>
  AuthType Sample::AuthCookieHandler
  AuthName WhatEver
  SetHandler perl-script
  PerlHandler Sample::AuthCookieHandler->login
 </Files>

DESCRIPTION

Apache::AuthCookie allows you to intercept a user's first unauthenticated access to a protected document. The user will be presented with a custom form where they can enter authentication credentials. The credentials are posted to the server where AuthCookie verifies them and returns a session key.

The session key is returned to the user's browser as a cookie. As a cookie, the browser will pass the session key on every subsequent accesses. AuthCookie will verify the session key and re-authenticate the user.

All you have to do is write a custom module that inherits from AuthCookie. Your module is a class which implements two methods:

authen_cred()

Verify the user-supplied credentials and return a session key. The session key can be any string - often you'll use some string containing username, timeout info, and any other information you need to determine access to documents, and append a one-way hash of those values together with some secret key.

authen_ses_key()

Verify the session key (previously generated by authen_cred(), possibly during a previous request) and return the user ID. This user ID will be fed to $r->connection->user() to set Apache's idea of who's logged in.

By using AuthCookie versus Apache's built-in AuthBasic you can design your own authentication system. There are several benefits.

  1. The client doesn't *have* to pass the user credentials on every subsequent access. If you're using passwords, this means that the password can be sent on the first request only, and subsequent requests don't need to send this (potentially sensitive) information. This is known as "ticket-based" authentication.

  2. When you determine that the client should stop using the credentials/session key, the server can tell the client to delete the cookie. Letting users "log out" is a notoriously impossible-to-solve problem of AuthBasic.

  3. AuthBasic dialog boxes are ugly. You can design your own HTML login forms when you use AuthCookie.

  4. You can specify the domain of a cookie using PerlSetVar commands. For instance, if your AuthName is WhatEver, you can put the command

     PerlSetVar WhatEverDomain .yourhost.com

    into your server setup file and your access cookies will span all hosts ending in .yourhost.com.

This is the flow of the authentication handler, less the details of the redirects. Two REDIRECT's are used to keep the client from displaying the user's credentials in the Location field. They don't really change AuthCookie's model, but they do add another round-trip request to the client.


 (-----------------------)     +---------------------------------+
 ( Request a protected   )     | AuthCookie sets custom error    |
 ( page, but user hasn't )---->| document and returns            |
 ( authenticated (no     )     | FORBIDDEN. Apache abandons      |      
 ( session key cookie)   )     | current request and creates sub |      
 (-----------------------)     | request for the error document. |<-+
                               | Error document is a script that |  |
                               | generates a form where the user |  |
                 return        | enters authentication           |  |
          ^------------------->| credentials (login & password). |  |
         / \      False        +---------------------------------+  |
        /   \                                   |                   |
       /     \                                  |                   |
      /       \                                 V                   |
     /         \               +---------------------------------+  |
    /   Pass    \              | User's client submits this form |  |
   /   user's    \             | to the LOGIN URL, which calls   |  |
   | credentials |<------------| AuthCookie->login().            |  |
   \     to      /             +---------------------------------+  |
    \authen_cred/                                                   |
     \ function/                                                    |
      \       /                                                     |
       \     /                                                      |
        \   /            +------------------------------------+     |
         \ /   return    | Authen cred returns a session      |  +--+
          V------------->| key which is opaque to AuthCookie.*|  |
                True     +------------------------------------+  |
                                              |                  |
               +--------------------+         |      +---------------+
               |                    |         |      | If we had a   |
               V                    |         V      | cookie, add   |
  +----------------------------+  r |         ^      | a Set-Cookie  |
  | If we didn't have a session|  e |T       / \     | header to     |
  | key cookie, add a          |  t |r      /   \    | override the  |
  | Set-Cookie header with this|  u |u     /     \   | invalid cookie|
  | session key. Client then   |  r |e    /       \  +---------------+
  | returns session key with   |  n |    /  pass   \               ^    
  | sucsesive requests         |    |   /  session  \              |    
  +----------------------------+    |  /   key to    \    return   |
               |                    +-| authen_ses_key|------------+
               V                       \             /     False
  +-----------------------------------+ \           /
  | Tell Apache to set Expires header,|  \         /
  | set user to user ID returned by   |   \       /
  | authen_ses_key, set authentication|    \     /
  | to our type (e.g. AuthCookie).    |     \   /
  +-----------------------------------+      \ /
                                              V
         (---------------------)              ^
         ( Request a protected )              |
         ( page, user has a    )--------------+
         ( session key cookie  )
         (---------------------)


 *  The session key that the client gets can be anything you want.  For
    example, encrypted information about the user, a hash of the
    username and password (similar in function to Digest
    authentication), or the user name and password in plain text
    (similar in function to HTTP Basic authentication).

    The only requirement is that the authen_ses_key function that you
    create must be able to determine if this session_key is valid and
    map it back to the originally authenticated user ID.

METHODS

Apache::AuthCookie has several methods you should know about. Here is the documentation for each. =)

  • authenticate()

    This method is one you'll use in a server config file (httpd.conf, .htaccess, ...) as a PerlAuthenHandler. If the user provided a session key in a cookie, the authen_ses_key() method will get called to check whether the key is valid. If not, or if there is no key provided, we redirect to the login form.

  • authorize()

    This will step through the require directives you've given for protected documents and make sure the user passes muster. The require valid-user and require user joey-jojo directives are handled for you. You can implement custom directives, such as require species hamster, by defining a method called hamster() in your subclass, which will then be called. The method will be called as $r->hamster($r, $args), where $args is everything on your require line after the word hamster. The method should return OK on success and FORBIDDEN on failure.

    Currently users must satisfy ALL of the require directives. I have heard that other Apache modules let the user satisfy ANY of the require directives. I don't know which is correct, I haven't found any Apache docs on the matter. If you need one behavior or the other, be careful. I may change it if I discover that ANY is correct.

  • authen_cred()

    You must define this method yourself in your subclass of Apache::AuthCookie. Its job is to create the session key that will be preserved in the user's cookie. The arguments passed to it are:

     sub authen_cred ($$\@) {
       my $self = shift;  # Package name (same as AuthName directive)
       my $r    = shift;  # Apache request object
       my @cred = @_;     # Credentials from login form
    
       ...blah blah blah, create a session key...
       return $session_key;
     }

    The only limitation on the session key is that you should be able to look at it later and determine the user's username. You are responsible for implementing your own session key format. A typical format is to make a string that contains the username, an expiration time, whatever else you need, and an MD5 hash of all that data together with a secret key. The hash will ensure that the user doesn't tamper with the session key. More info in the Eagle book.

  • authen_ses_key()

    You must define this method yourself in your subclass of Apache::AuthCookie. Its job is to look at a session key and determine whether it is valid. If so, it returns the username of the authenticated user.

     sub authen_ses_key ($$$) {
       my ($self, $r, $session_key) = @_;
       ...blah blah blah, check whether $session_key is valid...
       return $ok ? $username : undef;
     }
  • login()

    This method handles the submission of the login form. It will call the authen_cred() method, passing it $r and all the submitted data with names like "credential_#", where # is a number. These will be passed in a simple array, so the prototype is $self->authen_cred($r, @credentials). After calling authen_cred(), we set the user's cookie and redirect to the URL contained in the "destination" submitted form field.

  • login_form()

    This method is responsible for displaying the login form. The default implementation will make an internal redirect and display the URL you specified with the PerlSetVar WhatEverLoginForm configuration directive. You can overwrite this method to provide your own mechanism.

  • logout()

    This is simply a convenience method that unsets the session key for you. You can call it in your logout scripts. Usually this looks like $r->auth_type->logout($r);.

  • send_cookie($session_key)

    By default this method simply sends out the session key you give it. If you need to change the default behavior (perhaps to update a timestamp in the key) you can override this method.

  • recognize_user()

    If the user has provided a valid session key but the document isn't protected, this method will set $r->connection->user anyway. Use it as a PerlFixupHandler, unless you have a better idea.

  • key()

    This method will return the current session key, if any. This can be handy inside a method that implements a require directive check (like the species method discussed above) if you put any extra information like clearances or whatever into the session key.

UPGRADING FROM VERSION 1.4

There are a few interface changes that you need to be aware of when migrating from version 1.x to 2.x. First, the authen() and authz() methods are now deprecated, replaced by the new authenticate() and authorize() methods. The old methods will go away in a couple versions, but are maintained intact in this version to ease the task of upgrading. The use of these methods is essentially the same, though.

Second, when you change to the new method names (see previous paragraph), you must change the action of your login forms to the location /LOGIN (or whatever URL will call your module's login() method). You may also want to change their METHOD to POST instead of GET, since that's much safer and nicer to look at (but you can leave it as GET if you bloody well want to, for some god-unknown reason).

Third, you must change your login forms (see "THE LOGIN SCRIPT" below) to indicate how requests should be redirected after a successful login.

Fourth, you might want to take advantage of the new logout() method, though you certainly don't have to.

EXAMPLE

For an example of how to use Apache::AuthCookie, you may want to check out the test suite, which runs AuthCookie through a few of its paces. The documents are located in t/eg/, and you may want to peruse t/real.t to see the generated httpd.conf file (at the bottom of real.t) and check out what requests it's making of the server (at the top of real.t).

THE LOGIN SCRIPT

You will need to create a login script (called login.pl above) that generates an HTML form for the user to fill out. You might generate the page using an Apache::Registry script, or an HTML::Mason component, or perhaps even using a static HTML page. It's usually useful to generate it dynamically so that you can define the 'destination' field correctly (see below).

The following fields must be present in the form:

  1. The ACTION of the form must be /LOGIN (or whatever you defined in your server configuration as handled by the ->login() method - see example in the SYNOPSIS section).

  2. The various user input fields (username, passwords, etc.) must be named 'credential_0', 'credential_1', etc. on the form. These will get passed to your authen_cred() method.

  3. You must define a form field called 'destination' that tells AuthCookie where to redirect the request after successfully logging in. Typically this value is obtained from $r->prev->uri. See the login.pl script in t/eg/.

In addition, you might want your login page to be able to tell the difference between a user that sent an incorrect auth cookie, and a user that sent no auth cookie at all. These typically correspond, respectively, to users who logged in incorrectly or aren't allowed to access the given page, and users who are trying to log in for the first time. To help you differentiate between the two, AuthCookie will set $r->subprocess_env('AuthCookieReason') to either bad_cookie or no_cookie. You can examine this value in your login form by examining $r->prev->subprocess_env('AuthCookieReason') (because it's a sub-request).

Of course, if you want to give more specific information about why access failed when a cookie is present, your authen_ses_key() method can set arbitrary entries in $r->subprocess_env.

THE LOGOUT SCRIPT

If you want to let users log themselves out (something that can't be done using Basic Auth), you need to create a logout script. For an example, see t/eg/logout.pl. Logout scripts may want to take advantage of AuthCookie's logout() method, which will set the proper cookie headers in order to clear the user's cookie. This usually looks like $r->auth_type->logout($r);.

Note that if you don't necessarily trust your users, you can't count on cookie deletion for logging out. You'll have to expire some server-side login information too. AuthCookie doesn't do this for you, you have to handle it yourself.

ABOUT SESSION KEYS

Unlike the sample AuthCookieHandler, you have you verify the user's login and password in authen_cred(), then you do something like:

    my $date = localtime;
    my $ses_key = MD5->hexhash(join(';', $date, $PID, $PAC));

save $ses_key along with the user's login, and return $ses_key.

Now authen_ses_key() looks up the $ses_key passed to it and returns the saved login. I use Oracle to store the session key and retrieve it later, see the ToDo section below for some other ideas.

KNOWN LIMITATIONS

If the first unauthenticated request is a POST, it will be changed to a GET after the user fills out the login forms, and POSTed data will be lost.

TO DO

  • There ought to be a way to solve the POST problem in the LIMITATIONS section. It involves being able to re-insert the POSTed content into the request stream after the user authenticates.

    It might be nice if the logout method could accept some parameters that could make it easy to redirect the user to another URI, or whatever. I'd have to think about the options needed before I implement anything, though.

AUTHOR

Ken Williams, ken@forum.swarthmore.edu

Originally written by Eric Bartley, bartley@purdue.edu

SEE ALSO

perl(1), mod_perl(1), Apache(1).