Apache服務器的用戶認證 (轉)
Jun 21, 2016 am 09:14 AMapache|服務器
經(jīng)常上網(wǎng)的讀者會遇到這種情況:訪問一些網(wǎng)站的某些資源時,瀏覽器彈出一個對話框,要求輸入用戶名和密碼來獲取對資源的訪問。這就是用戶認證的一種技術。用戶認證是保護網(wǎng)絡系統(tǒng)資源的第一道防線,它控制著所有登錄并檢查訪問用戶的合法性,其目標是僅讓合法用戶以合法的權限訪問網(wǎng)絡系統(tǒng)的資源?;镜挠脩粽J證技術是“用戶名+密碼”。
Apache是目前流行的Web服務器,可運行在Linux、Unix、Windows等操作系統(tǒng)下,它可以很好地解決“用戶名+密碼”的認證問題。Apache用戶認證所需要的用戶名和密碼有兩種不同的存貯方式:一種是文本文件;另一種是MSQL、Oracle、MySQL等數(shù)據(jù)庫。下面以Linux的Apache為例,就這兩種存貯方式,分別介紹如何實現(xiàn)用戶認證功能,同時對Windows的Apache用戶認證作簡要的說明。
采用文本文件存儲
這種認證方式的基本思想是:Apache啟動認證功能后,就可以在需要限制訪問的目錄下建立一個名為.htaccess的文件,指定認證的配置命令。當用戶第一次訪問該目錄的文件時,瀏覽器會顯示一個對話框,要求輸入用戶名和密碼,進行用戶身份的確認。若是合法用戶,則顯示所訪問的頁面內容,此后訪問該目錄的每個頁面,瀏覽器自動送出用戶名和密碼,不用再輸入了,直到關閉瀏覽器為止。以下是實現(xiàn)的具體步驟:
以超級用戶root進入Linux,假設Apache 1.3.12已經(jīng)編譯、安裝到了/usr/local/apache目錄中。缺省情況下,編譯Apache時自動加入mod_auth模塊,利用此模塊可以實現(xiàn)“用戶名+密碼”以文本文件為存儲方式的認證功能。
1.修改Apache的配置文件/usr/local/apache/conf/httpd.conf,對認證資源所在的目錄設定配置命令。下例是對/usr/local/apache/htdocs/members目錄的配置:
?。糄irectory /usr/local/apache/htdocs /members>
Options Indexes FollowSymLinks
allowoverride authconfig
order allow,deny
allow from all
?。?Directory>
其中,allowoverride authconfig一行表示允許對/usr/local/apache/htdocs/ members目錄下的文件進行用戶認證。
2.在限制訪問的目錄/usr/local/apache/htdocs/members下建立一個文件.htaccess,其內容如下:
AuthName "會員區(qū)"
AuthType basic
AuthUserFile/usr/local/apache/members.txt
require valid-user
說明:文件.htaccess中常用的配置命令有以下幾個:
1) AuthName命令:指定認證區(qū)域名稱。區(qū)域名稱是在提示要求認證的對話框中顯示給用戶的(見附圖)。
2)AuthType命令:指定認證類型。在HTTP1.0中,只有一種認證類型:basic。在HTTP1.1中有幾種認證類型,如:MD5。
3) AuthUserFile命令:指定一個包含用戶名和密碼的文本文件,每行一對。
4) AuthGroupFile命令:指定包含用戶組清單和這些組的成員清單的文本文件。組的成員之間用空格分開,如:
managers:user1 user2
5) require命令:指定哪些用戶或組才能被授權訪問。如:
require user user1 user2(只有用戶user1和user2可以訪問)
requiresgroupsmanagers (只有組managers中成員可以訪問)
require valid-user (在AuthUserFile指定的文件中任何用戶都可以訪問)
3.利用Apache附帶的程序htpasswd,生成包含用戶名和密碼的文本文件:/usr/local/apache/members.txt,每行內容格式為“用戶名:密碼”。
#cd /usr/local/apache/bin
#htpasswd -bc ../members.txt user1 1234
#htpasswd -b ../members.txt user2 5678
文本文件members.txt含有兩個用戶:user1,口令為1234;user2,口令為5678。注意,不要將此文本文件存放在Web文檔的目錄樹中,以免被用戶下載。
欲了解htpasswd程序的幫助,請執(zhí)行htpasswd -h。
當用戶數(shù)量比較少時,這種方法對用戶的認證是方便、省事的,維護工作也簡單。但是在用戶數(shù)量有數(shù)萬人,甚至數(shù)十萬人時,會在查找用戶上花掉一定時間,從而降低服務器的效率。這種情形,應采用數(shù)據(jù)庫方式。
采用數(shù)據(jù)庫存儲
目前,Apache、PHP4、MySQL三者是Linux下構建Web網(wǎng)站的最佳搭檔,這三個軟件都是免費軟件。將三者結合起來,通過HTTP協(xié)議,利用PHP4和MySQL,實現(xiàn)Apache的用戶認證功能。
只有在PHP4以Apache的模塊方式來運行的時候才能進行用戶認證。為此,在編譯Apache時需要加入PHP4模塊一起編譯。假設PHP4作為Apache的模塊,編譯、安裝Apache到/usr/local/apache目錄,編譯、安裝MySQL到/usr/local/mysql目錄。然后進行下面的步驟:
1.在MySQL中建立一個數(shù)據(jù)庫member,在其中建立一個表users,用來存放合法用戶的用戶名和密碼。
1)用vi命令在/tmp目錄建立一個SQL腳本文件auth.sql,內容為:
drop database if exists member;
create database member;
use member;
create table users (
username char(20) not null,
password char(20) not null,
);
insertsintosusers values("user1",password("1234"));
insertsintosusers values("user2",password("5678"));
2)啟動MySQL客戶程序mysql,執(zhí)行上述SQL腳本文件auth.sql的命令,在表users中增加兩個用戶的記錄。
#mysql -u root -pmypwd</tmp/auth.sql
2.編寫一個PHP腳本頭文件auth.inc,程序內容為:
?。?php
function authenticate() {
Header('WWW-authenticate: basic realm="會員區(qū)"');
Header('HTTP/1.0 401 Unauthorized');
echo "你必須輸入正確的用戶名和口令。 ";
exit;
}
function CheckUser(, ) {
if ( == "" || == "") return 0;
= "SELECT username,password FROM usersswheresusername='' and password=password('')";
= mysql_connect('localhost', 'root', 'mypwd');
mysql_select_db('member',);
= mysql_query(, );
=mysql_num_rows();
mysql_close();
if (>0) {
return 1; //有效登錄
} else {
return 0; //無效登錄
}
}
?>
函數(shù)Authenticate()的作用是利用函數(shù)Header('WWW-authenticate: basic realm="會員區(qū)"'),向瀏覽器發(fā)送一個認證請求消息,使瀏覽器彈出一個用戶名/密碼的對話框。當用戶輸入用戶名和密碼后,包含此PHP腳本的URL將自動地被再次調用,將用戶名、密碼、認證類型分別存放到PHP4的三個特殊變量:、、,在PHP程序中可根據(jù)這三個變量值來判斷是否合法用戶。Header()函數(shù)中,basic表示基本認證類型,realm的值表示認證區(qū)域名稱。
函數(shù)Header('HTTP/1.0 401 Unauthorized')使瀏覽器用戶在連續(xù)多次輸入錯誤的用戶名或密碼時接收到HTTP 401錯誤。
函數(shù)CheckUser()用來判斷瀏覽器用戶發(fā)送來的用戶名、密碼是否與MySQL數(shù)據(jù)庫的相同,若相同則返回1,否則返回0。其中mysql_connect('localhost', 'root', 'mypwd')的數(shù)據(jù)庫用戶名root和密碼mypwd,應根據(jù)自己的MySQL設置而改變。
3.在需要限制訪問的每個PHP腳本程序開頭增加下列程序段:
?。?php
require('auth.inc');
if (CheckUser(,)==0) {
authenticate();
} else {
echo "這是合法用戶要訪問的網(wǎng)頁。"; //將此行改為向合法用戶輸出的網(wǎng)頁
}
?>
把需要向合法用戶顯示的網(wǎng)頁內容放到else子句中,取代上述程序段的一行:
echo "這是合法用戶要訪問的網(wǎng)頁。";
這樣,當用戶訪問該PHP腳本程序時,需要輸入用戶名和密碼來確認用戶的身份。
Windows的Apache用戶認證
1.采用文本文件存放用戶名和密碼時,其方法同前,但需要注意的是表示路徑的目錄名之間、目錄名與文件名之間一律用斜線“/”分開,而不是反斜線“”。
2.采用MySQL數(shù)據(jù)庫存放用戶名和密碼時,首先按下列方法將PHP 4.0.3作為Apache的模塊來運行,然后按上述“采用數(shù)據(jù)庫存儲用戶名和密碼的用戶認證”的方法完成。
1)下載Windows版的Apache 1.3.12、PHP 4.0.3、MySQL 3.2.32,將三個軟件分別解壓、安裝到C:pache、C:PHP4、C:mysql目錄。
2) C:PHP4SAPI目錄有幾個常用Web服務器的PHP模塊文件,將其中php4apache.dll拷貝到Apache的modules子目錄(C:pachemodules)。
3)修改Apache的配置文件C:pachenfhttpd.conf,增加以下幾行:
LoadModule php4_module modules/ php4apache.dll
AddType application/x-httpd-php .php3
AddType application/x-httpd-php-source .phps
AddType application/x-httpd-php .php
第一行使PHP4以Apache的模塊方式運行,這樣才能進行用戶認證,后三行定義PHP腳本程序的擴展名。
4)在autoexec.bat文件的PATH命令中增加PHP4所在路徑“C:PHP4”,重新啟動電腦。
經(jīng)我測試,2.0版本的apache不成

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

CTE is a temporary result set in MySQL used to simplify complex queries. It can be referenced multiple times in the current query, improving code readability and maintenance. For example, when looking for the latest orders for each user in the orders table, you can first obtain the latest order date for each user through the CTE, and then associate it with the original table to obtain the complete record. Compared with subqueries, the CTE structure is clearer and the logic is easier to debug. Usage tips include explicit alias, concatenating multiple CTEs, and processing tree data with recursive CTEs. Mastering CTE can make SQL more elegant and efficient.

Reasons and solutions for the header function jump failure: 1. There is output before the header, and all pre-outputs need to be checked and removed or ob_start() buffer is used; 2. The failure to add exit causes subsequent code interference, and exit or die should be added immediately after the jump; 3. The path error should be used to ensure correctness by using absolute paths or dynamic splicing; 4. Server configuration or cache interference can be tried to clear the cache or replace the environment test.

The method of using preprocessing statements to obtain database query results in PHP varies from extension. 1. When using mysqli, you can obtain the associative array through get_result() and fetch_assoc(), which is suitable for modern environments; 2. You can also use bind_result() to bind variables, which is suitable for situations where there are few fields and fixed structures, and it is good compatibility but there are many fields when there are many fields; 3. When using PDO, you can obtain the associative array through fetch (PDO::FETCH_ASSOC), or use fetchAll() to obtain all data at once, so the interface is unified and the error handling is clearer; in addition, you need to pay attention to parameter type matching, execution of execute(), timely release of resources and enable error reports.

In PHP, you can use a variety of methods to determine whether a string starts with a specific string: 1. Use strncmp() to compare the first n characters. If 0 is returned, the beginning matches and is not case sensitive; 2. Use strpos() to check whether the substring position is 0, which is case sensitive. Stripos() can be used instead to achieve case insensitive; 3. You can encapsulate the startsWith() or str_starts_with() function to improve reusability; in addition, it is necessary to note that empty strings return true by default, encoding compatibility and performance differences, strncmp() is usually more efficient.

WhensettingupMySQLtables,choosingtherightdatatypesiscrucialforefficiencyandscalability.1)Understandthedataeachcolumnwillstore—numbers,text,dates,orflags—andchooseaccordingly.2)UseCHARforfixed-lengthdatalikecountrycodesandVARCHARforvariable-lengthdata
