美文网首页nginx
nginx配置指令auth_basic、auth_basic_u

nginx配置指令auth_basic、auth_basic_u

作者: boldcautious | 来源:发表于2018-01-10 15:25 被阅读3682次

    配置示例

    location / {
        auth_basic           "my site";
        auth_basic_user_file conf/htpasswd;
    }
    

    指令说明

    auth_basic

    语法: auth_basic string | off;
    默认值: auth_basic off;
    上下文: http,server,location,limit_except

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

    另外auth_basic指定的字符串会在弹窗中显示。


    Firefox弹窗中显示auth_basic指定的字符串
    IE弹窗中显示auth_basic指定的字符串

    auth_basic_user_file

    语法: auth_basic_user_file file;
    默认值: —
    上下文: http,server,location,limit_except

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

    # comment
    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,密码为12345的示例如下

    htpasswd

    [root@test ~]# /opt/apache/bin/htpasswd -bdc htpasswd admin 12345
    Adding password for user admin
    [root@test ~]# cat htpasswd
    admin:PbSRr7orsxaso

    openssl passwd

    [root@test ~]# openssl passwd 12345
    fIHcRVEKijgoM
    [root@test ~]# echo "admin:fIHcRVEKijgoM" > htpasswd
    [root@test ~]# cat htpasswd
    admin:fIHcRVEKijgoM

    变量说明

    $remote_user
    为HTTP基本认证提供的用户名。例如上述图和示例中提到的用户admin。

    补充说明

    auth_basic、auth_basic_user_file指令由ngx_http_auth_basic_module模块提供。

    HTTP基本认证的流程如下:

    1. 客户端发送HTTP请求给服务器,服务器验证该用户是否已经登录验证过了,如果没有的话,服务器会返回一个401 Unauthozied给客户端,并且在响应头的WWW-Authenticate字段中添加相关信息。如下图所示:


    2. 浏览器在接收到401响应后,会弹出登录验证的对话框。用户输入用户名和密码后,浏览器用BASE64编码,放在请求头的Authorization字段中发送给服务器。如下图:


    3. 服务器将Authorization字段中的用户名密码取出,进行验证,如果验证通过,将根据请求,发送资源给客户端。如果验证失败服务器还会返回401给客户端,继续重复步骤2和步骤3。

    nginx可以通过如下几种方式来限制访问

    • 密码,即HTTP基本认证,ngx_http_auth_basic_module模块
    • 地址,ngx_http_access_module模块
    • 子请求结果,ngx_http_auth_request_module模块,1.5.4+
    • JWT,ngx_http_auth_jwt_module模块,1.11.3

    使用satisfy指令就能限制是否需要同时通过地址和密码来限制访问。

    另外,Linux命令行中,可以通过如下命令验证HTTP基本认证:

    curl -u username:password URL

    curl -u admin:12345 http://127.0.0.1

    相关文章

      网友评论

        本文标题:nginx配置指令auth_basic、auth_basic_u

        本文链接:https://www.haomeiwen.com/subject/mxznnxtx.html