使用nginx给网站添加身份认证

使用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
用户名:密码:注释
  1. 使用htpasswd工具加密密码

    sudo apt install apache2-utils
    sudo htpasswd /usr/local/nginx/conf/htpasswd username //输入两遍密码
    
  2. 修改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;
    
  3. 重启nginx服务

    sudo nginx -t
    sudo nginx -s reload
    
  4. 去浏览器验证现在访问域名下的资源都需要先登陆认证才可以

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

原文地址:https://www.cnblogs.com/super-lulu/p/11741591.html