Text only
University of Aberdeen Takes you to the main page for this section

WWW Information Pack

Factsheet 20: How can I restrict access to my web pages?

Topics covered: .htaccess files, restricting access by user location, restricting access by password, PHP-based password protection, Basic HTTP authentication , HTTP headers, MySQL database-driven authentication systems, PHP libraries.

20.1 Introduction

Although most web pages are intended to be visible to the world, there may be times when you want to make your pages accessible only to a certain group of users (e.g. only users within the University of Aberdeen, or only users to whom you have previously given a password). This chapter describes some techniques by which you can achieve this.

20.2 What is a .htaccess file, and how does it work?

The University of Aberdeen's central web server runs the UNIX operating system and the Apache web server software (see www.apache.org). On this web server platform, it is possible to restrict access to your web pages by means of a special file named .htaccess

(Note, however, that Microsoft Windows-based servers, running Microsoft's Internet Information Services (IIS) web server software, do not recognise or obey the commands in .htaccess files, so the instructions that follow are relevant to Apache-based web servers only.)

A .htaccess file is written in plain text (ASCII) format. It can contain security information which instructs the Apache web server whether or not to deliver your web pages in response to a particular request.

A .htaccess file needs to be stored and published in the same directory as the web pages that it protects. It will then regulate web-based access to all of the files in that directory (plus any sub-directories of it).

20.3 How can I use a .htaccess file to restrict access by the user's location?

The following example allows you to restrict access to your web pages to users located within the University of Aberdeen.

Using a plain text editor (such as Notepad), create the following text file:

AuthUserFile /dev/null
AuthGroupFile /dev/null
AuthName "Example of access from Aberdeen only"
AuthType Basic
<Limit GET POST>
order deny,allow
deny from all
allow from .abdn.ac.uk
</Limit>

Save this file in the directory containing the web pages that you wish to protect (this will usually be a sub-folder inside your H:\public.htm folder). Give it the filename .htaccess

Note - some text editors such as Notepad will try to insert the extension .txt onto the end of this filename (i.e. .htaccess.txt) which will prevent the file from working. To avoid this, try placing quote marks around the filename, e.g.: ".htaccess" when you save your file (Figure 20.1).

detail of the Save As... dialogue box, showing the filename .htaccess enclosed between double-quotes

Figure 20.1 - Enclosing the filename .htaccess within quote-marks (in the Save As... dialogue box) should prevent your text editor from automatically adding a .txt extension

(UNIX experts can alternatively create a .htaccess file inside their public_html web space using a standard UNIX text editor such as emacs or pico within a telnet terminal session.)

Now run the University of Aberdeen's standard web publishing procedure, using either the UNIX www.publish command or its equivalent at www.abdn.ac.uk/local/publish/ (see Factsheet 10 for an explanation of this process).

If you have completed these instructions successfully, then the web pages within your protected directory should still be visible as normal from a University of Aberdeen networked computer. However, users outside the University will receive a 403 Forbidden error message from the web server when they try to view these pages (Figure 20.2).

a 403 Forbidden error page from the Univesity of Aberdeen

Figure 20.2 - A '403 Forbidden' error from the University of Aberdeen web server - this should be obtained by anyone attempting to view your protected web page from outside the University of Aberdeen network.

If you are working within the University, but need to check that your pages are protected against viewers from outside the University, you can try submitting the URL of one of your protected pages to an external validation service such as validator.w3.org - this service should then report a "403 Forbidden" error when it tries to retrieve your page.

20.4 How can I use a .htaccess file to restrict access by user-id and password? [advanced topic]

The .htaccess system can be extended to give access only to specific users, each with their own password.

To do this, it is necessary to be comfortable with logging in to the University's UNIX system and issuing commands - if you find this too unfamiliar, then you may prefer the alternative PHP-based approach discussed below (Section 20.5).

Create a .htaccess file in the protected directory, in the same way as above. This time, the .htaccess file should contain the following:

AuthUserFile /{your path}/abc123/passfile
AuthGroupFile /dev/null
AuthName ByPassword
AuthType Basic
<Limit GET POST>
require valid-user
</Limit>

where abc123 is your own user-id, and {your path} is the UNIX path to your own home filespace: you can find this out by logging in to sysa and typing: echo ~

So if your user-id was psy023, for example, then the top line would be:

AuthUserFile /home/nof-a-psy/psy023/passfile

This time, you will need a second file - one which contains the list of users and passwords whom you are going to allow to view your pages. In this example, we have assumed that the file will be called passfile and will be stored in your home (root) directory. You can actually call it by any name you like, and store it anywhere within your filespace, provided that the name and path are correctly given in the AuthUserFile line above. But for the sake of security, it is best not to store this password file inside your public_html directory, or any of its sub-directories.

To create your password file, use the UNIX htpasswd command with the -c option, to add the first user and password to the list:

sysa% cd ~
(changing back to root directory, because this is where we have specified that the password file will be located)

sysa% htpasswd -c passfile john
Adding password for john
New password: (type in the password you want to use here)
Re-type new password: (and again)

To add subsequent users to the list, omit the -c option:

sysa% htpasswd passfile sarah
Adding user sarah
New password: (type in password here)
Re-type new password: (and again)

At the end of this process, you will have a file called passfile in your home filespace, which contains the valid users and their passwords (in encrypted format):

sysa% more passfile
john:eVdV2AfMXk0nU
sarah:bqTcB2GcSggTo

This file also needs to be published for web access before it will function properly. The University of Aberdeen's standard web publishing procedure (Factsheet 10) should be sufficient to achieve this.

Now whenever any user attempts to view web pages within your protected directory, they will be prompted for a username and password (Figure 20.3). Only the two valid combinations that you defined when creating your passfile will allow access to these pages.

A browser dialogue box prompting for a user-id and password

Figure 20.3 - When attempting to access a password-protected page, the browser prompts the user for their username and password.

20.5 How can I password-protect my pages with PHP scripts, rather than .htaccess files?

An alternative method of password-protecting your pages is to use the PHP server-side scripting language (see Factsheet 18 for an introduction to working with PHP).

Using PHP, we can protect our web pages by means of Basic HTTP authentication - which means that the authentication instructions are sent between the web server and the client browser in the HTTP headers.

(HTTP headers are pieces of information that are routinely exchanged 'behind the scenes' between the web server and the client during the course of their normal HTTP request-response interaction. PHPs header() function allows us to specify additional information to be sent out to the browser via the HTTP headers. For more information about HTTP headers, see www.edginet.org/techie/website/http.html or www.wdvl.com/Internet/Protocols/HTTP/Headers.html.)

Here is a very simple example of how to protect a web page, using PHP's header() function to enable basic HTTP authentication:

<?php
if ( $PHP_AUTH_USER != "guest" || $PHP_AUTH_PW != "let_me_in" ) {
  header('WWW-Authenticate: Basic realm="My Protected Area"');
  header("HTTP/1.1 401 Unauthorized");
  echo "Failed to log in.";
  exit();
  }
else {
  echo "You are logged in successfully as: ".$PHP_AUTH_USER;
  echo "PLACE PROTECTED CONTENT IN HERE";
  }
?>

The above PHP script checks first to see whether two special variables called $PHP_AUTH_USER and $PHP_AUTH_PW are set to the correct values - you would need to specify your own username and password values in the script at this point, to replace the examples "guest" and "let_me_in" shown above.

In the first instance, this test will be false (because the user has not yet supplied a username and password). The appropriate HTTP authentication headers are therefore generated by the script and sent back to the user's web browser. This causes the browser to display its familiar Username/Password pop-up dialogue box (Figure 20.3).

When the user types their authentication details into this box, and clicks OK, the PHP script is run again. This time, the username and password supplied by the user are loaded into the PHP variables $PHP_AUTH_USER and $PHP_AUTH_PW, and again tested against their correct values as specified in the script. If these details are now correct, then the user is able to see the protected content.

This example will provide a reasonable level of protection for your pages. However, you should not consider it sufficient to protect extremely sensitive information. Some security considerations that are relevant to the above simple example are as follows:

20.6 More advanced web page protection systems using PHP and databases [advanced topic]

Using more advanced PHP coding techniques, it is possible to construct much more sophisticated and secure user authentication systems.

Two very useful PHP user authentication scripts are provided at www.abdn.ac.uk/local/php/. Both of these example scripts require the user to log in using their central University user-id and password. Using these scripts, you can therefore restrict access to your pages to University of Aberdeen members only (although they can access your pages both from within the University network and from outside).

In one of these example scripts, the user's login details are checked against a database of users held on a Microsoft Active Directory LDAP server. (LDAP stands for Lightweight Directory Access Protocol and is a standard method of storing and searching information about people.) The other script checks the same information against the University's central password file.

Alternatively, if you need to build your own user authentication system from first principles, you might choose to store the user-ids and passwords of your users in a MySQL database table. When a user logs in, you could use a PHP script to compare the password that they supply against the correct password that is stored for them in the database. An introduction to the principles of web-database development using PHP and MySQL is provided in Factsheet 19.

However, before embarking upon such an ambitious development, it is worth noting that a number of pre-written Open Source libraries of PHP code are freely available, which contain sophisticated user authentication functionality. References to these libraries, and tutorials on how to use them, are provided below.

You may encounter published examples of PHP applications that base their authentication systems upon the use of session variables - these are variables that can hold a certain value for the duration of the user's browser session, and can therefore be used in any of the pages that they visit. Session variables are sometimes used for maintaining the status of an authenticated user within a complex web system, as they move from page to page. However, it is not advisable to rely solely upon session variables for authentication in a web-based application, because they are less than fully secure. One user's session can potentially be "captured" by another unscrupulous user - see www.abdn.ac.uk/local/php/doc/ref.session.html for further discussion.


Further information

Tutorials and further information on the use of .htaccess files are available at:
www.freewebmasterhelp.com/tutorials/htaccess/
www.javascriptkit.com/howto/htaccess.shtml
www.theriver.com/trwrc/htaccess.html
httpd.apache.org/docs/howto/htaccess.html

More information about LDAP is available at:
www.kingsmountain.com/ldapRoadmap.shtml
www.innosoft.com/ldapworld/ldapfaq.html

PHP-based user authentication is discussed in detail at:
www.zend.com/zend/tut/authentication.php

Techniques for building a PHP-MySQL user administration system are described in the book Beginning PHP4 by W. Choi et. al., published by Wrox, 2000, ISBN 186100373

The following pages provide tutorials and downloadable code for three PHP libraries with sophisticated built-in user authentication functionality:

patUser:
www.devshed.com/Server_Side/PHP/patUser/patUser1/page1.html
www.php-tools.de

Uma:
www.neverwillbes.com/uma/
sourceforge.net/projects/rampart

PHPlib:
phplib.sourceforge.net
www.wdvl.com/Authoring/Languages/PHP/Session_Management/
www.linux-mag.com/2002-03/lamp_01.html
www.cyber.com.au/users/clancy/phplib.html


Download Factsheet as PDF
contents page Contents page  Next Factsheet Next Factsheet


Valid XHTML 1.0!

 Text only View this page as text only


University Home · Prospective students · Prospectuses · A to Z Index · Search · Email & Telephone · Maps & Travel · Contacts

University Switchboard: +44 (0)1224 272000
Enquiries about studying at Aberdeen should be directed to sras@abdn.ac.uk
Central pages designed and maintained by Web Team
Comments about the web site? - Email the Web Team
Please read our Privacy Policy & Disclaimer (PDF) and Accessibility Policy (PDF)
All photographs and text copyright © 2004 University of Aberdeen
Last Modified: Friday, 19-Dec-2008 13:31:15 GMT