使用nginx給網站添加身份認證
basic auth
默認情況下nginx已經安裝了ngx_http_auth_basic_module模塊,如果不需要這個模塊,可以加上 --without-http_auth_basic_module 。
nginx basic auth指令
語法: auth_basic string | off;
默認值: auth_basic off;
配置段: http, server, location, limit_except
默認表示不開啟認證,后面如果跟上字符,這些字符會在彈窗中顯示。
語法: auth_basic_user_file file;
默認值: —
配置段: http, server, location, limit_except
用戶密碼文件,文件內容類似如下:
username:passwd:comment
用戶名:密碼:注釋
-
使用htpasswd工具加密密碼
sudo apt install apache2-utils sudo htpasswd /usr/local/nginx/conf/htpasswd username //輸入兩遍密碼
-
修改nginx配置
sudo vim /usr/local/nginx/conf/nginx.conf 在http段添加: auth_basic "nginx basic http auth test for auth.test.com"; auth_basic_user_file /usr/local/nginx/conf/htpasswd; autoindex_exact_size off; autoindex_localtime on; autoindex on;
-
重啟nginx服務
sudo nginx -t sudo nginx -s reload
-
去瀏覽器驗證現在訪問域名下的資源都需要先登陸認證才可以
ngx_http_auth_request_module 第三方認證
編譯 Nginx 時需要添加該模塊 --with-http_auth_request_module
該模塊可以將客戶端輸入的用戶名、密碼 username:password 通過 Base64 編碼后寫入 Request Headers 中
例如:wang:wang -> Authorization:Basic d2FuZzp3YW5n=
然后通過第三方程序解碼后跟數據庫中用戶名、密碼進行比較,Nginx 服務器通過 header 的返回狀態判斷是否認證通過。
- 編輯nginx配置文件
server {
listen 80;
server_name local.server.com;
auth_request /auth;
location / {
root html;
index index.html;
}
location /auth {
proxy_pass http://auth.server.com/HttpBasicAuthenticate.php;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header X-Original-URI $request_uri;
}
}
# auth_request /auth; # 啟用認證
# proxy_pass http://auth.server.com/HttpBasicAuthenticate.php; # 認證服務器地址
# 參考地址:http://nginx.org/en/docs/http/ngx_http_auth_request_module.html
-
添加第三方認證服務器
vim /usr/local/nginx/conf/vhost/auth.conf # 這是第三方認證服務器,認證邏輯使用的 PHP 代碼 server { listen 80; server_name auth.server.com; root /usr/local/nginx/auth; location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /usr/local/nginx-1.10.2/html$fastcgi_script_name; include fastcgi_params; } }
-
添加認證程序
vim /usr/local/nginx/auth/HttpBasicAuthenticate.php <?php if(isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])){ $username = $_SERVER['PHP_AUTH_USER']; $password = $_SERVER['PHP_AUTH_PW']; if ($username == 'wang' && $password == '123456'){ return true; } } header('WWW-Authenticate: Basic realm="Git Server"'); header('HTTP/1.0 401 Unauthorized');
-
用戶訪問 local.server.com 彈出框中輸入的用戶名、密碼保存在 $_SERVER 變量中
中間 if 段,只做演示用,工作中應該是拿用戶輸入的用戶名、密碼跟數據庫中的數據做比較
用戶訪問 local.server.com 就會去 auth.servere.com 做用戶認證,認證通過后繼續訪問 local.server.com