Wednesday, 12 September 2012

Authenticating HTTP Users Using htpasswd and .htaccess


htpasswd is used to create and update the flat-files used to store usernames and password for basic authentication of HTTP users. htpasswd encrypts passwords using either a version of MD5 modified for Apache, or the system’s crypt() routine.
htpasswd returns a zero status (“true”) if the username and password have been successfully added or updated in the password file. htpasswd returns 1 if it encounters some problem accessing files, 2 if there was a syntax problem with the command line, 3 if the password was entered interactively and the verification entry didn’t match, 4 if its operation was interrupted, 5 if a value is too long (username, filename, password, or final computed record), 6 if the username contains illegal characters (see the Restrictions section), and 7 if the file is not a valid password file.
Following steps will guide you to create password protected directories in Apache.

1. Create a password file for user ‘ganesh’ using htpasswd command

htpasswd -c /home/user/.htpasswd ganesh
This will create a new file and stores a record in it for user ganesh. The user is prompted for the password. If the file exists and cannot be read, or cannot be written, it is not altered and htpasswd will display a message and return an error status.

2. Add/modify password for ganesh

htpasswd /home/user/.htpasswd ganesh
The user is prompted for the password which will get added to the password file.
In order to implement web based authentication (password protected directories), you need to modify the user’s .htaccess file (if it is not available under the ‘Document Root’ of the user, you need to create it) with the following entries.
AuthType Basic
AuthName “Restricted Access”
AuthUserFile /home/user/.htpasswd
Require user ganesh
Note: If the webserver has disabled the usage of .htaccess file, you can enable it for the user, by modifying the apache configuration file (httpd.conf). Check for the <Directory> directive for the directory for which you need to enable .htaccess.
Replace,
AllowOverride None
With,
AllowOverride AuthConfig

No comments:

Post a Comment