Nginx配置auth_basic身份验证(401验证)

袁志蒙 607次浏览

摘要:Nginx开启使用“HTTP基本认证”(HTTP Basic Authentication)协议的用户名密码验证,指定的参数被用作域,auth_basic配置示例: location / { auth_basic "Authorization"; auth_basic_user_file /etc/nginx/conf/htpasswd; }

auth_basic配置示例:

location / {
    auth_basic           "Authorization";
    auth_basic_user_file /etc/nginx/conf/htpasswd;
}

Nginx开启使用“HTTP基本认证”(HTTP Basic Authentication)协议的用户名密码验证。指定的参数被用作域。参数可以包含变量(1.3.10,1.2.7)。参数off可以取消继承自上一个配置等级auth_basic指令的影响。参数off表示不开启HTTP基本认证,另外auth_basic指定的字符串会在弹窗中显示。

auth_basic_user_file

语法: auth_basic_user_file file;

默认值: —

上下文: http,server,location,limit_except

指定保存用户名密码的文件,格式如下:

name1:password1
name2:password2:comment
name3:password3
#用户名:密码:注释

参数file中可以包含变量。

密码应该使用crypt()函数加密。可以用Apache HTTP Server发行包中的htpasswd命令或者openssl passwd来创建此类文件。

参数file可以是文件、相对路径的文件、绝对路径的文件。非绝对路径下,文件的位置是相对于nginx安装路径下的conf目录的。比如nginx的安装路径是/usr/local/nginx,则设置对应的路径举例说明如下:

auth_basic_user_file htpasswd;
# htpasswd在机器上的位置:/usr/local/nginx/conf/htpasswd
auth_basic_user_file conf/htpasswd;
# htpasswd在机器上的位置:/usr/local/nginx/conf/conf/htpasswd
auth_basic_user_file /tmp/htpasswd;
# htpasswd在机器上的位置:/tmp/htpasswd

创建用户名为admin,密码为123456的示例如下 (htpasswd文件名可任意修改):

echo -e "admin:$(openssl passwd -crypt 123456)" > htpasswd

nginx_http_auth_request_module 第三方认证

编译 Nginx 时需要添加该模块 --with-http_auth_request_module

该模块可以将客户端输入的用户名、密码 username:password 通过 Base64 编码后写入 Request Headers 中,然后通过第三方程序解码后跟数据库中用户名、密码进行比较,Nginx 服务器通过 header 的返回状态判断是否认证通过。

检查是否安装 nginx_http_auth_request_module 模块:

nginx -V

编辑nginx配置文件

server {
	    listen 80;
	    server_name local.server.com;

	    location / {
	    	# 启用认证
            auth_request /auth;

            # 请求不是文件或路径,则访问跟目录下的/index.php
            try_files $uri $uri/ /index.php?$query_string;
        }
        
        location /auth {
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header REMOTE-HOST $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Original-URI $request_uri;
            proxy_pass_request_body off;
            proxy_set_header Content-Length "";

            # 认证服务器地址
            proxy_pass http://localhost:8080/HttpBasicAuthenticate.php;
        }
}

PHP认证程序

<?php
if(isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])){
    $username = $_SERVER['PHP_AUTH_USER'];
    $password = $_SERVER['PHP_AUTH_PW'];

    if ($username == 'admin' && $password == '123456'){
        return true;
    }
}

header('WWW-Authenticate: Basic realm="Git Server"');
header('HTTP/1.0 401 Unauthorized');

重启nginx

sudo nginx -t
sudo nginx -s reload


随机内容

表情

共0条评论
  • 这篇文章还没有收到评论,赶紧来抢沙发吧~