Skip to content

身份验证(Auth Basic)配置

参考

auth basic 官方文档

https://nginx.org/en/docs/http/ngx_http_auth_basic_module.html

Details
The ngx_http_auth_basic_module module allows limiting access to resources by validating the user name and password using the “HTTP auth basic ntication” protocol.

Access can also be limited by address, by the result of subrequest, or by JWT. Simultaneous limitation of access by address and by password is controlled by the satisfy directive.

Example Configuration

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

Directives

Syntax:	auth_basic string | off;
Default:
auth_basic off;
Context:	http, server, location, limit_except

Enables validation of user name and password using the “HTTP auth basic ntication” protocol. The specified parameter is used as a realm. Parameter value can contain variables (1.3.10, 1.2.7). The special value off cancels the effect of the auth_basic directive inherited from the previous configuration level.

Syntax: auth_basic_user_file file;
Default: —
Context: http, server, location, limit_except

Specifies a file that keeps user names and passwords, in the following format:

# comment

name1:password1
name2:password2:comment
name3:password3

The file name can contain variables.

The following password types are supported:

  • encrypted with the crypt() function; can be generated using the “htpasswd” utility from the Apache HTTP Server distribution or the “openssl passwd” command;
  • hashed with the Apache variant of the MD5-based password algorithm (apr1); can be generated with the same tools;
  • specified by the “{scheme}data” syntax (1.0.3+) as described in RFC 2307; currently implemented schemes include PLAIN (an example one, should not be used), SHA (1.3.13) (plain SHA-1 hashing, should not be used) and SSHA (salted SHA-1 hashing, used by some software packages, notably OpenLDAP and Dovecot).
Support for SHA scheme was added only to aid in migration from other web servers. It should not be used for new passwords, since unsalted SHA-1 hashing that it employs is vulnerable to rainbow table attacks.

这段英文翻译成中文是:

ngx_http_auth_basic_module 模块允许通过使用“HTTP 基本认证”协议验证用户名和密码来限制访问资源。

访问也可以通过地址、子请求的结果或 JWT 来限制。同时限制地址和密码的访问由 satisfy 指令控制。

示例配置:

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

指令

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

使用“HTTP 基本认证”协议验证用户名和密码。指定的参数用作领域。参数值可以包含变量(从版本 1.3.10, 1.2.7 开始支持)。特殊值 off 取消从上一配置级别继承的 auth_basic 指令的效果。

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

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

# 评论

name1:password1
name2:password2:评论
name3:password3

文件名可以包含变量。

支持以下密码类型:

  • 使用 crypt() 函数加密;可以使用 Apache HTTP Server 分发的“htpasswd”工具或“openssl passwd”命令生成;
  • 使用基于 MD5 的 Apache 变体密码算法 (apr1) 哈希;可以使用同样的工具生成;
  • 使用 “{scheme}data” 语法(自 1.0.3 版本起)指定,如 RFC 2307 中描述;当前实现的方案包括 PLAIN(示例方案,不应使用)、SHA (1.3.13)(纯 SHA-1 哈希,不应使用)和 SSHA(带盐的 SHA-1 哈希,一些软件包使用,特别是 OpenLDAP 和 Dovecot)。

INFO

只为了帮助从其他网络服务器迁移而添加了对 SHA 方案的支持。由于它使用的未加盐的 SHA-1 哈希容易受到彩虹表攻击,因此不应用于新密码。

auth basic 模块介绍

ngx_http_auth_basic_module 是 Nginx 中用于实现基本的 HTTP 认证的模块。这种认证方法依赖于 HTTP 标准中的“基本认证”机制,通过要求用户提供用户名和密码来控制对网站或其特定部分的访问。

1. auth basic 主要功能

  • 用户验证:验证访问者是否提供了有效的用户名和密码。
  • 简单配置:易于配置,只需简单地在 Nginx 配置文件中指定用户名和密码文件即可。
  • 基本安全:虽然不提供高级加密(密码通过 Base64 编码传输,容易被解码),但可以为不敏感的应用提供基本的安全层。

2. auth basic 配置方法

要启用基本认证,你需要在 Nginx 的配置文件中设置 auth_basic 指令和 auth_basic_user_file 指令。这里是一个基本的示例:

  • 启用认证:使用 auth_basic 指令在特定的 location 或整个 server 中启用基本认证。
  • 用户文件:使用 auth_basic_user_file 指令指定存储用户名和密码的文件路径。

3. auth basic 示例配置

nginx
server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;
    location / {
        auth_basic "Restricted Area";  # 启用基本认证并设置 realm
        auth_basic_user_file /etc/nginx/.htpasswd;  # 指定密码文件
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

在这个示例中,当用户尝试访问任何内容时,都会被要求输入用户名和密码。密码文件 .htpasswd 可以使用 Apache 提供的 htpasswd 工具来生成。

4. auth basic 注意事项

  • 安全性:由于 HTTP 基本认证传输的是未加密的密码,建议在使用基本认证的同时启用 SSL/TLS,即通过 HTTPS 来提高传输过程中的安全性。
  • 密码管理:密码文件需要妥善管理和定期更新,以防止安全风险。
  • 性能影响:基本认证可能会稍微影响服务器的响应时间,因为每个请求都需要进行用户名和密码的验证。

通过 ngx_http_auth_basic_module,即使在没有复杂用户管理系统的情况下,也可以快速为网站添加一层基本的访问控制。这种方法特别适合小型应用或开发环境中的临时安全需求。

生成 nginx auth basic 所需的密码文件

1. 编写 Dockerfile

创建 password.Dockerfile 文件

powershell

ni password.Dockerfile

或者

bash
touch password.Dockerfile

password.Dockerfile

Dockerfile
# 使用 Alpine Linux 作为基础镜像
FROM alpine:latest

# 安装 apache2-utils,其中包含 htpasswd 工具
RUN apk --no-cache add apache2-utils

# 设置容器的入口点为执行 htpasswd 命令
ENTRYPOINT ["sh", "-c", "htpasswd -cb /output/.htpasswd $0 $1"]

2. 构建镜像,安装 apache2-utils

使用 Dockerfile 文件 'password.Dockerfile' 构建一个名为 'password-generator' 的 Docker 镜像

bash
docker build -t password-generator -f password.Dockerfile .

3. 运行容器生成密码文件

对于 macOS 或 Linux 系统:

使用 'password-generator' 镜像启动一个 Docker 容器,将当前目录 (pwd) 挂载到容器的 /output 目录

容器在执行完毕后自动删除 (--rm),并传递 'username' 和 'password' 作为参数

bash
docker run --rm -v $(pwd):/output password-generator username password

对于 Windows 系统:

与上面的 Bash 命令相同,但这里使用 PowerShell 语法来获取当前目录 (${PWD})

同样将当前目录挂载到容器的 /output 目录,并传递 'username' 和 'password' 作为参数

powershell
docker run --rm -v ${PWD}:/output password-generator username password

添加 nginx auth basic 配置

运行 nginx 命名为 myauth 容器

bash
docker run --name myauth -d -p 80:80 nginx

获取默认的 default.conf

bash
docker cp  myauth:/etc/nginx/conf.d/default.conf default.conf

删除 myauth 容器

bash
docker rm -f myauth

修改 location 添加 auth basic

default.conf

nginx
server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;

    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        auth_basic "Restricted Area";  # 启用基本认证并设置 realm
        auth_basic_user_file /etc/nginx/.htpasswd;  # 指定密码文件
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

创建 Dockerfile 文件,内容如下

Dockerfile
# 使用最新版本的 nginx 作为基础镜像
FROM nginx:latest

# 将 .htpasswd 文件复制到 nginx 的配置目录中
COPY .htpasswd /etc/nginx/.htpasswd

# 将自定义的 nginx 配置文件复制到默认配置目录中
COPY default.conf /etc/nginx/conf.d/default.conf

构建镜像 nginx-auth-basic

bash
docker build -t nginx-auth-basic .

运行容器 mynginx

bash
docker run --name mynginx -d -p 8081:80 nginx-auth-basic

访问查看效果 http://localhost:8081

alt text

其他的 nginx auth 模块介绍

ngx_http_auth_jwt_module 模块介绍

ngx_http_auth_jwt_module 模块是 Nginx 的一个扩展模块,用于通过 JSON Web Tokens (JWT) 来验证 HTTP 请求的认证。这种模块使得 Nginx 能够校验客户端请求中的 JWT,并基于此来决定是否允许访问指定的资源。使用 JWT 认证能够提供比基本认证更安全、更灵活的访问控制机制。

  1. 主要功能
  • 验证 JWT:该模块检查 HTTP 请求中的 JWT(通常在请求头中的 Authorization 字段),验证其有效性,包括签名的验证以及其他标准的声明,如 issuer(发行者)、audience(观众)、expiration time(过期时间)等。
  • 灵活的配置:可以在 Nginx 配置中详细配置 JWT 的处理方式,例如配置密钥、期望的签名算法、JWT 应该包含的必要声明等。
  • 访问控制:根据 JWT 的有效性以及其中包含的信息(如用户角色、权限标识等),控制用户对资源的访问。
  1. 使用场景
  • 单点登录(SSO):在多个服务或应用之间提供无缝的用户体验,用户登录一次后,可以使用 JWT 在其他服务中进行认证。
  • 微服务架构:在微服务架构中,服务间调用通常需要认证和授权。JWT 是一种轻量级的方式来实现服务间的安全调用。
  • API 安全:对外提供的 API 可以使用 JWT 进行保护,确保只有拥有有效令牌的用户才能访问。
  1. 配置示例

这里是一个基本的 Nginx 配置示例,展示了如何使用 ngx_http_auth_jwt_module

nginx
location /protected {
    auth_jwt "Restricted";  # 启用 JWT 认证,并设置 realm 为 "Restricted"
    auth_jwt_key_file /path/to/key;  # 指定存储 JWT 验证密钥的文件路径
}

在这个示例中,访问 /protected 路径的请求需要包含有效的 JWT。JWT 的签名将使用指定密钥文件中的密钥进行验证。

通过 ngx_http_auth_jwt_module,Nginx 可以直接处理基于 JWT 的认证,无需依赖后端应用程序进行认证,从而提高性能并简化架构。

ngx_http_auth_request_module 模块介绍

ngx_http_auth_request_module 是 Nginx 的一个非常有用的模块,它允许通过子请求向指定的服务进行认证。这个模块使得 Nginx 能够在转发主请求到后端服务器之前,先将一个内部子请求发送到另一个内部位置进行认证。如果这个子请求返回成功(即 HTTP 状态码 200),那么主请求就会被处理;如果子请求返回失败(例如 HTTP 状态码 401 或 403),则主请求会被拒绝。

  1. 主要功能
  • 解耦认证逻辑:将认证逻辑与应用逻辑分离,允许使用独立的认证服务,这对于构建大型、复杂的系统尤其有用。
  • 灵活的认证策略:可以根据不同的需求配置不同的认证服务,例如不同的 API 可以使用不同的认证机制。
  • 提高性能和安全性:通过减轻后端应用服务器的负担,专注于业务逻辑的同时,保证通过认证的请求更安全。
  1. 使用场景
  • 中心化认证服务:为所有请求提供一个统一的认证服务,例如 OAuth、SSO 或自定义的认证系统。
  • 微服务架构中的服务网关:在微服务架构中,ngx_http_auth_request_module 可以用作服务网关,管理各种服务的认证。
  • 条件访问控制:根据用户的登录状态或权限动态允许或拒绝对特定资源的访问。
  1. 示例配置
nginx
location /protected {
    # 在转发请求到 /protected 之前,先发送一个子请求到 /auth
    auth_request /auth;
    # 可以设置子请求的响应失败时返回的状态码,默认是 401
    auth_request_set $auth_status $upstream_status;
}

# 子请求的处理位置
location = /auth {
    # 这里可以配置转发到具体的认证服务,如一个 HTTP API
    proxy_pass http://auth-service/validate;
    proxy_set_header Content-Length "";
    proxy_pass_request_body off;
}

在这个配置中,当有请求尝试访问 /protected 路径时,Nginx 会首先将请求转发到 /auth 路径。在 /auth 中,请求被进一步转发到一个名为 auth-service 的服务进行验证。如果 auth-service 返回 HTTP 200 状态,主请求将继续;如果返回 HTTP 401 或 403,访问将被拒绝。

ngx_http_auth_request_module 的使用可以极大地提高大型系统中的认证灵活性和效率,是构建现代互联网应用架构的有力工具。