Authentication using .htaccess

It is quite easy to create web server access restriction using the Cpanel. There is a configuration setting for "Password Protect Directories" in Cpanel for setting up a user name and password for directory access. What this really does is to create a password file and refer it in the .htaccess.

In stead of using Cpanel, one can always run the process through the command line and it may actually be easier.

Create the passwd file

htpasswd is an Apache utility command to create and update the flat-files used to store usernames and password for basic authentication of HTTP users. Since it will create name and password pair(s) in a flat file, the password is encrypted either using a MD5 version from Apache or crypt() system call.

The following command line can be used to generate a file name passwdfile:

htpasswd -c /home/user/etc/passwdfile admin

his will create a NEW passwdfile and add user "admin" in it. The command will also prompt for the password that you wish to give to this user.

To add a new user, the "-c" option cannot be used.

To remove a user, simply open the htpasswd file and delete the line.

Modify .htaccess

To turn the password into effect, you can add  the following lines in the .htacess file:

AuthType Basic
AuthName "Restricted Area"
AuthUserFile "/home/user/etc/passwdfile"
require valid-user

This will allow anyone in the .htpasswd file to have access.

Besides the flat text password file, one can also use alternate password storage such as DBM or DBD format according to Apache document.

Group the users

There maybe situations that there are a lot of users and they are granted access to different resources. It maybe easier to group the users instead of creating a bunch of .htpasswd files.

A group file is simply a flat file that contains some user names. An admin group file (let's call it admingroup) may look like this:

Admin: admin jdoe mjones

And the .htaccess should include the following:

AuthType Basic
AuthName "Admin Group Only"
AuthUserFile "/home/user/etc/htpasswd" "/home/user/etc/.dmingroup"
Require group Admin

 

As specified in .htaccess, this is really just a "basic" way for authentication. It is most suitable for a small group of users to access some resource and there is no need to create more sophisticated authenticated method.

This entry was posted in security. Bookmark the permalink.