HTTP Basic Authentication協(xié)議
ngx_http_auth_basic_module
模塊使用HTTP Basic Authentication
協(xié)議來驗證用戶名和密碼,從而實現(xiàn)對資源的訪問限制。HTTP Basic Authentication
協(xié)議相關(guān)
- 客戶端請求web服務(wù)器時,如果返回
401
Unauthorized表示需要身份認(rèn)證,響應(yīng)頭中會包含WWW-Authenticate
字段,例如WWW-Authenticate: Basic realm="closed site"
,realm
表示認(rèn)證域,瀏覽器收到這個響應(yīng)后會彈出用戶名密碼輸入框。 - 客戶端發(fā)送認(rèn)證信息,在請求頭中
Authorization
字段中傳入用戶名和密碼。格式為Authorization:Basic Base64(用戶名:密碼)
。 HTTP Basic Authentication
認(rèn)證通過以后瀏覽器會緩存認(rèn)證信息,下次訪問時能夠看到瀏覽器會在請求中自動加上Authorization
頭信息。
auth_basic指令
- 作用:啟用
HTTP Basic Authentication
認(rèn)證。 - 語法:
auth_basic string | off;
auth_basic string
表示啟用HTTP Basic Authentication
認(rèn)證。auth_basic off
取消繼承自上一層的auth_basic
指令的設(shè)置。
- 作用域:
http, server, location, limit_except
auth_basic_user_file指令
2. 語法:auth_basic_user_file file;
指定認(rèn)證文件,文件格式為:
user1:password1
user2:password2
crypt()
函數(shù)加密,可以通過Apache HTTP Server的htpasswd工具生成,或openssl passwd命令生成。- 安裝:sudo yum install httpd-tools
- 加密:
htpasswd -s conf/htpasswd user1
# 使用SHA1算法生成user1用戶的密碼并更新到conf/htpasswd
文件中
- 系統(tǒng)一般都預(yù)裝了openssl
- openssl passwd -6 -salt "bKaMt2" 3edc4rfv # 使用SHA512算法對3edc4rfv加密,生成后的密碼手動加入到htpasswd文件中,格式為:
用戶名:加密后的密碼
- htpasswd或openssl passwd工具計算的MD5值。
- htpasswd:
htpasswd -m -s conf/htpasswd user5
# MD5算法配置user5用戶的密碼并更新到conf/htpasswd
文件中 - openssl方式:
openssl passwd -1 34erdfcv
# MD5算法對3edc4rfv加密,生成后的密碼手動加入到conf/htpasswd
文件中,格式為:用戶名:加密后的密碼
- RFC 2307定義的
{scheme}data
格式。scheme
為加密方案,可以為PLAIN、SHA、SSHA
;data
為Base64編碼的數(shù)據(jù)。 - PLAIN方式加密舉例:PLAIN是明文方式,不推薦,格式為:
user7:{PLAIN}8ik7uj
,其中user7為用戶名,8ik7uj為密碼。 - SHA方式加密舉例:
printf "123qwe" | openssl dgst -sha1 -binary | base64
# 對123qwe加密,生成后手動加入到htpasswd文件中,格式為:用戶名:{SHA}加密后的密碼
- 安裝:
sudo yum install openldap-servers openldap-clients
- 加密 :
slappasswd -h "{SSHA}" -s "3edc3edc"
# 對3edc3edc加密,生成后手動加入到htpasswd文件中,格式為:用戶名:{SSHA}加密后的密碼
測試
- nginx配置
location /test {
auth_basic "closed site";
auth_basic_user_file /usr/local/nginx/conf/htpasswd;
alias /usr/local/nginx/html;
}
- 測試
curl --request GET \
--url http://xxx.xxx.xxx.xxx/test/index.html \
--header 'Accept: */*' \
--header 'Accept-Encoding: gzip, deflate, br' \
--header 'Authorization: Basic dXNlcjk6M2VkYzNlZGM=' \
--header 'Connection: keep-alive' \
--header 'User-Agent: PostmanRuntime-ApipostRuntime/1.1.0'
閱讀原文:原文鏈接
該文章在 2025/7/1 23:38:33 編輯過