Configure Apache server user authentication

Source: Internet
Author: User
Tags http authentication mysql client

Readers who frequently access the Internet may encounter this situation: when accessing some resources of some websites, a dialog box pops up in the browser asking users and passwords to access resources. This is a technology used for user authentication. User authentication is the first line of defense to protect network system resources. It controls all logins and checks the validity of users, the goal is to only allow legal users to access network system resources with legal permissions. The basic user authentication technology is "User Name + password ".

 

Apache is a popular Web server that runs on Linux, UNIX, windows, and other operating systems. It can well solve the authentication problem of "User Name + password.
The username and password required for Apache user authentication are stored in two different ways: text files and databases such as msql, Oracle, and MySQL.

 

The following uses Linux Apache as an example to describe how to implement user authentication based on these two storage methods.

I. Text File Storage

The basic idea of this authentication method is: after Apache starts the authentication function, you can create a directory named. specifies the authentication configuration command. When you access the file in this directory for the first time, the browser displays a dialog box asking you to enter the user name and password to confirm your identity. If the user is a legal user, the content of the accessed page is displayed. After that, the browser automatically sends out the user name and password and does not need to enter the password until the browser is closed.

The specific steps are as follows:

Assume that Apache has been compiled and installed in the/usr/local/Apache directory. By default, the mod_auth module is automatically added when Apache is compiled,
This module can be used to authenticate the user name and password stored in text files.
(Run the following command to check whether the specified module has been installed in Apache,/usr/local/Apache/bin/apachectl-l)

1. Modify the Apache configuration file/usr/local/Apache/CONF/httpd. conf and set the configuration command for the directory where the authentication resource is located.
In the following example, configure the/data/home/tenfyguo/proj/Soso/htdocs directory and add the following configurations to the corresponding virtual machine configuration:

<Directory/data/home/tenfyguo/proj/Soso/htdocs>
Options indexes followsymlinks
AllowOverride authconfig # the key is to add this sentence
Order allow, deny
Allow from all
</Directory>

AllowOverride authconfig indicates that user authentication is allowed for files in the/data/home/tenfyguo/proj/Soso/htdocs directory.

2. Create a file. htaccess (actually a hidden file) under the/data/home/tenfyguo/proj/Soso/htdocs directory with restricted access. Its content is as follows:

Authname "the text here is displayed in the prompt logon window displayed in the browser"
Authtype basic
Authuserfile/data/home/tenfyguo/proj/Soso/valid.txt # Put the user name and password file here, not where the file can be downloaded
Require valid-user

Note: common configuration commands in file. htaccess include the following:

1) authname command: Specify the authentication region name. The region name is displayed to the user in the prompt authentication dialog box.
2) authtype command: Specify the authentication type. In http1.0, there is only one authentication type: Basic. There are several authentication types in http1.1, such as MD5.
3) authuserfile command: specify a text file containing the user name and password. Each line has a pair.
4) authgroupfile: Specifies a text file that contains a list of user groups and a list of members of these groups. Group members are separated by spaces, for example:
Managers: user1 user2
5) require command: Specify which users or groups can be accessed with authorization. For example:
Require user user1 user2 (only users user1 and user2 can access)
Requires groups managers (only members in the group managers can access)
Require valid-user (any user can access the file specified by authuserfile)

3. Use the program htpasswd that comes with Apache to generate a text file containing the user name and password:/data/home/tenfyguo/proj/Soso/valid.txt,
The format of each line is "User name: Password ".

# Cd/usr/local/Apache/bin
# Htpasswd-BC/data/home/tenfyguo/proj/Soso/valid.txt user 1 1234
# Htpasswd-B/data/home/tenfyguo/proj/Soso/valid.txt user 2 5678

The text file/data/home/tenfyguo/proj/Soso/valid.txt contains two users: user1, password 1234, user2, and password 5678.

Open the text file and you will find that the password is encrypted.
Note: Do not store this text file in the directory tree of the Web document to avoid being downloaded by users.

To learn more about the htpasswd program, run htpasswd-H.

Restart Apache to make the configuration take effect.
/Usr/local/Apache/bin/apachectl restart
 
When the user opens the browser request for the first time: http://test.soso.com: 13601/test/, the browser will pop up a prompt box for the user to enter the user name and password. View Apache response in a package:
(1) Apache response:
HTTP/1.1 401 authorization required
Date: Thu, 27 Jan 2011 11:10:07 GMT
Server: Apache/2.2.4 (UNIX)
WWW-Authenticate: Basic realm = "test"
Content-Length: 401
Keep-alive: timeout = 5, max = 100
Connection: keep-alive
Content-Type: text/html; charset = iso-8859-1

<! Doctype HTML public "-// IETF // dtd html 2.0 // en">
<HTML> <Title> 401 authorization required</title>
</Head> <body>
<H1> authorization required <P> This server cocould not verify that you
Are authorized to access the document
Requested. Either you supplied the wrong
Credentials (e.g., bad password), or your
Browser doesn' t understand how to supply
The credentials required. </P>
</Body>

 

It can be seen that the status code returned by Apache is 401, corresponding prompt information: anthorization required, and a very important response header is returned:
WWW-Authenticate: Basic realm = "test"

(2) In the browser pop-up prompt box, ask the user to enter the user name and password, and then the browser will send the following message:
GET/test/HTTP/1.1
HOST: test.soso.com: 13601
User-Agent: Mozilla/5.0 (windows; U; Windows NT 5.1; ZH-CN; RV: 1.9.2.13) Gecko/20101203 Firefox/3.6.13
Accept: text/html, application/XHTML + XML, application/XML; q = 0.9, */*; q = 0.8
Accept-language: ZH-CN, ZH; q = 0.5
Accept-encoding: gzip, deflate
Accept-charset: gb2312, UTF-8; q = 0.7, *; q = 0.7
Keep-alive: 115
Connection: keep-alive
If-modified-since: Fri, 12 Jun 2009 03:43:20 GMT
Authorization: Basic dgvuznlndw86dgvuznlndw8 =

 

As you can see, the browser adds the request header to the request:
Authorization: Basic dgvuznlndw86dgvuznlndw8 =
Apache uses this header for permission verification.

When the number of users is small, this method is convenient and easy to authenticate, And the maintenance work is also simple. However, when there are tens of thousands or even hundreds of thousands of users,
It takes some time to search for users, thus reducing the server efficiency. In this case, the database method should be used.

 

2. database storage

Currently, Apache, PHP, and MySQL are the best web site construction partners in Linux. These three software are free software. Combine the three methods and use PHP and MySQL through the HTTP protocol to implement Apache user authentication.
User authentication can be performed only when PHP runs in Apache module mode. Therefore, you must add the PHP module to compile Apache. Suppose PHP is used as the Apache module to compile and install Apache to the/usr/local/Apache directory, and compile and install MySQL to the/usr/local/MySQL directory. Perform the following steps:

1. Create a database member in MySQL, and create a table users in it to store the username and password of Valid users.

1) Use the VI command to create an SQL script file Auth. SQL IN THE/tmp directory. The content is:
Drop datebase if exists member;
Create Database member;
Use member;
Create Table users (
Username char (20) not null,
Password char (20) not null,
);

Insert into users values ("user1", password ("1234 "));
Insert into users values ("user2", password ("5678 "));

 

2) Start MYSQL client program MySQL, execute the auth. SQL command in the preceding SQL script file, and add two user records in the users table.

# Mysql-u root-pmypwd </tmp/auth. SQL

 

2. Write a PHP script header file Auth. Inc. The program content is:
<? PHP
/*
"Php_auth_user"
When PHP runs in the Apache module mode and uses the HTTP authentication function, this variable is the user name entered by the user.
"Php_auth_pw"
When PHP runs in the Apache module mode and is using the HTTP authentication function, this variable is the password entered by the user.
"Auth_type"
When PHP runs in the Apache module mode and uses the HTTP authentication function, this variable is the authentication type.
*/

 

Function authenticate (){
Header ("HTTP/1.0 401 authorization required ");
Header ("www-Authenticate: Basic realm = 'test '");
Echo "Enter the authenticated user name and password ";
Exit;
}

 

Function check_user (){
If (isset ($ _ server ['php _ auth_user ']) & isset ($ _ server ['php _ auth_pw']) {
// Here, you can change it to access the database to obtain the user name and password.
If ($ _ server ['php _ auth_user '] = 'tenfyguo' & $ _ server ['php _ auth_pw'] = 'tenfyguo '){
Return 0;
}

Return-1;
}

Return-1;

}

 

If (check_user () <0 ){
Authenticate ();
}

Echo "verify normal ";
Exit;
?>

 

The authenticate () function uses the function header ("www-Authenticate: Basic realm = 'test'") to send an authentication request message to the browser,
Make the browser pop up a user name/Password dialog box. After the user enters the user name and password, the URL containing the PHP script is automatically called again,
The user name, password, and authentication type are stored in three special variables of PHP: "php_auth_user", "php_auth_pw", and "auth_type ", in PHP, you can determine whether the user is valid based on the three variable values.
In the header () function, basic indicates the basic authentication type, and the value of realm indicates the authentication region name.

 

Function header ("HTTP/1.0 401 authorization required") enables browser users to receive HTTP 401 errors when they enter incorrect usernames or passwords multiple times in a row.

    
The article Reprinted from the Network Manager House: http://www.bitscn.com/pdb/php/200701/95251.html and made some modifications according to the experiment.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.