Tuesday, April 8, 2008

modperl - PerlAuthenHandler

Let's say you are working on tenth of web services. All of them work perfectly.
And one day, your boss comes to you and says: "I need you to implement an Authorization mechanism for every web services".
How do you think you can do that?
You can create a class and edit every single handlers (web services) to handle authentication at the application level.
or
You can use the power of modperl and do this at the server level.

Apache runs several phases (some depends on your configuration) before running the actual code you want to serve (called the response handler).
Those phases can be found here

The interesting phase (or HTTP handler) for authentication is PerlAuthenHandler.

A basic configuration would be :

<Location /mywebservice/>
##############
# The below directives are mandatory in order
# to step in the PerlAuthenHandler phase
AuthType Basic
AuthName Test
Require valid-user
##############
SetHandler perl-script
PerlAuthenHandler MyAuthenticationModule
PerlResponseHandler MyWebService
</Location>


Only the "Basic" type of authentication is supported (at the moment?)
When running this phase, your favorite web browser would pop up a login window.
You would then have to implement your authentication mechanism in the handler set at PerlAuthenHandler (in our case MyAuthenticationModule).

The description of the PerlAuthenHandler is quite straight forward.

This type of Authentication is called "Basic HTTP Authentication". After successful authentication, for every requests your browser will send, the HTTP request header will contain a "Authorization" field containing your credentials (username/password) encrypted with an base-64 algorithm.
To reset the credentials, the server will have to call $r->note_basic_auth_failure and return a status code Apache2::Const::HTTP_UNAUTHORIZED.

If you want a fancy web interface to deal with Basic HTTP authentication, my advise is to forget about it as there is no way to reset credentials (if you want to simulate a timeout session) except with the method above, but you will always get the login window ...

So all you have to do is to edit the Apache configuration file and include the above directives without touching any code of your web services.

modpython also has access to HTTP handlers. It uses the same name as modperl for configuration directives (smart move). I m not sure if php has this feature of using Apache HTTP handlers, to investigate...

No comments: