Friday, April 15, 2011

Protecting website using basic authentication

Apache uses auth_mod to protect the whole or part of a site.
Here we will see how to provide access to your website to only authenticated users. I will demonstrate and explain the use of basic authentication.
In Apache’s main configuration file located at /etc/httpd/conf/httpd.conf or inside <VirtualHost></VirtualHost> directives, put in the following:
<Directory />
AuthName "Authentication Needed"
AuthType Basic
AuthUserFile /etc/httpd/conf/security_users
require valid-user
</Directory>
Let me explain the above directives one by one:
<Directory /> means that the directives applies to / , that is to the DocumentRoot of the site
AuthName creates a label that is displayed by web browsers to users.
AuthUserFile sets the file that Apache will consult to check user names and passwords for authenticating users.
AuthType specifies what type of authentication scheme to use
require directive stats that only valid users are allowed access to the site.
Now we have create the file that will hold the users and their passwords with the following command
htpasswd -c /etc/httpd/conf/security_users testuser
New password:
Re-type new password:
Adding password for user testuser
-c is meant to create the linuxgravity_access and testuser is the user to be created. The flag -c is not needed when adding any further users in the same file.
Now restart Apache.
/etc/init.d/apache2 restart
Access the site e.g. http://localhost or http://IP_of_apache

No comments:

Post a Comment