HOWO: Use Drupal For HTTP Authentication
Very often, a Drupal website is just one of many tools being deployed on a complex project. For instance, on Chapter Three's development servers, we keep our own SVN repositories to track custom modules and theme development.
Also often, miscellanious web services like this will want to use the standard HTTP Authentication system. Most simply this is the familiar pair a .haccess and .htpasswd file protecting a directory. Easy to set up, but it requires an admin to keep yet another list of usernames and passwords somewhere on the system which over time becomes quite a pain.
Today, while noodling with some authentication scripts for the Drupal Dojo, I decided to see if Drupal's own user table could be used as an authentication source for these tasks. Turns out it can, and it's pretty useful too.
Drupal User Authentication
First off, this requires mod_auth_mysql to be set up in your Apache server. There are packages for most systems, as this is a common and widely used Apache module. Once this is done, use the following code in a .htaccess file or Apache
AuthName "Use Your Drupal Login"<br />AuthType Basic<br />AuthMySQLEnable On<br />AuthMySQLHost <hostname><br />AuthMySQLDB <database><br />AuthMySQLUser <user><br />AuthMySQLPassword <password><br />AuthMySQLUserTable users<br />AuthMySQLNameField name<br />AuthMySQLPasswordField pass<br />AuthMySQLPwEncryption md5<br />require valid-user
Replace the hostname, database, user and pass values just as you would when configuring your drupal installation's setting.php file. This will let Apache access the same users table from Drupal and authenticate against it!
Limiting Access By Drupal User Role
For extra credit, you can restrict valid logins to a particular user role by replacing the AuthMySQLUserTable directive above with these two lines:
AuthMySQLUserTable "users, users_roles"<br />AuthMySQLUserCondition "users.uid = users_roles.uid AND users_roles.rid = 3"
The above assumes that your "admin" role has role id (rid) 3. Your mileage may vary here, and savvy SQL query writers will immediately see how you can use these two directives to limit access in all sorts of ways.
For admins with a lot of experience with mod-auth-mysql, this is all pretty obvious, but I hadn't seen documentation specific to Drupal anywhere on the web. Hopefully this will simplify your life as much as it's already simplifying mine!