「Nginx」- 配置基本认证(Basic Authentication)

  CREATED BY JENKINSBOT

问题描述

部分系统由于没有认证模块或者认证功能,因此所有人都能够访问。但是,我们并不希望被所有人访问,我们希望特定的有权限的用户才能访问。

因此,我们使用 Nginx 基础认证(Basic Authentication),实现在访问站点时提示用户进行基础认证。

该笔记将记录:在 Nginx 中,如何使用基本认证(Basic Auth)来进行访问控制,以及常见问题处理,还有一些高级的用法。

解决方法

第一步、添加用户

// 创建新的 .htpasswd 文件

# htpasswd -c /etc/apache2/.htpasswd "tom"
New password:
Re-type new password:
Adding password for user tom

// 追加用户到 .htpasswd 文件

# htpasswd /etc/apache2/.htpasswd "cat"
New password:
Re-type new password:
Adding password for user cat

// 验证添加成功

# cat /etc/apache2/.htpasswd
tom:$apr1$jf5bsAhN$/5nLq.A726iSqNWiAqdZ5/
cat:$apr1$qUV52OEi$vz0mUy6kXLrWcMh1aI3nD/

除了上述方法,还有种创建方法,虽然该方法会降低安全性,但也减少维护成本。Nginx 实现 RFC 2307 描述的语法,可以使用明文密码:

cat > /etc/apache2/.htpasswd <<EOF
username:{PLAIN}your-password
EOF

第二步、修改 Nginx 配置

server {
    ...
    auth_basic              "Administrator’s Area";
    auth_basic_user_file    /etc/apache2/.htpasswd;

    location /public/ {
        auth_basic off; # 在该地址下,关闭认证
    }
    ...
}

第三步、配置生效并验证

# systemctl reload nginx.service
# curl --user username:password http://example.com

常见问题汇总

在修改 Basic Auth 信息后,是否需要重启?

Does auth_basic changes require a service reload? – Server / NGINX – Ruby-Forum

添加或者修改 Basic Auth 信息,无需进行 Nginx 重启,因为 Basic Auth 文件是运行时动态加载的。

为特定网络地址禁用基本认证

Module ngx_http_core_module / satisfy
Module ngx_http_access_module
web server – How to disable http basic auth in nginx for a specific ip range? – Server Fault

server {
    ...
    satisfy any;

    # ngx_http_access_module
    allow <your ip address>;
    deny all;

    # ngx_http_auth_basic_module
    auth_basic              "Administrator’s Area";
    auth_basic_user_file    /etc/apache2/.htpasswd;
    ...
}

解释说明:配置 satisfy any; 表示只要通过 ngx_http_access_module, ngx_http_auth_basic_module, ngx_http_auth_request_module, ngx_http_auth_jwt_module 模块中的某个模块的检查,则允许进行访问。如上配置:我们的网络地址,通过 ngx_http_access_module 检查,允许访问;其他的网络地址,受到 ngx_http_access_module 限制,但是只要通过 ngx_http_auth_basic_module 的认证,依旧可以访问。

参考文献

NGINX Docs | Restricting Access with HTTP Basic Authentication
HTTP Basic Authentication – what’s the expected web browser experience? – Stack Overflow
Module ngx_http_auth_basic_module/auth_basic_user_file
RFC 2307 – An Approach for Using LDAP as a Network Information Service
Module ngx_http_auth_basic_module