Nginx ngx_http_auth_request_module模块鉴权

ngx_http_auth_request_module是什么?

ngx_http_auth_request_module模块 实现了基于一子请求的结果的客户端的授权。如果子请求返回2xx响应码,则允许访问。如果它返回401或403,则访问被拒绝并显示相应的错误代码。子请求返回的任何其他响应代码都被认为是错误的。
auth_request使用的也是subrequest进行子请求。

ngx_http_auth_request_module模块用途

当我们访问一个资源需要进行鉴权时,可以使用Nginxhttp_auth_request_module模块进行处理

ngx_http_auth_request_module使用

nginx配置文件

server {
    
    
        listen       8082;
        server_name  localhost;

        location /private {
    
    
            auth_request /auth;
            # 鉴权通过后的处理方式
            proxy_pass http://127.0.0.1:8002/auth/success;
        }

        location = /auth {
    
    
            # 鉴权服务器的地址
            proxy_pass http://127.0.0.1:8002/auth/token;
            proxy_pass_request_body off;
            proxy_set_header Content-Length "";
            proxy_set_header X-Original-URI $request_uri;
         }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
    
    
            root   html;
}

java 代码

package com.task.controller;

import cn.hutool.http.server.HttpServerRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wuzhenyong
 * ClassName:NginxAuthRequestController.java
 * date:2022-11-23 09:38
 * Description: 认证服务器
 */
@RestController
@RequestMapping("/auth")
public class NginxAuthRequestController {
    
    
    @GetMapping("/token")
    public Map<String, Object> token() {
    
    
        System.out.println("请求认证服务器接口" + LocalDateTime.now());
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("code", 200);
        result.put("msg", "成功");
        return result;
        // throw new RuntimeException("认证失败");
    }
    @GetMapping("/success")
    public Map<String, Object> success() {
    
    
        System.out.println("认证成功" + LocalDateTime.now());
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("code", 200);
        result.put("msg", "成功");
        return result;
    }
}

测试模拟认证成功

浏览器访问地址:http://localhost:8082/private

在这里插入图片描述

控制台打印:
在这里插入图片描述

模拟认证失败,抛出异常

代码变动:
在这里插入图片描述

重启项目访问测试:
在这里插入图片描述
返回的是nginx的错误页面哦,也可以自定义处理

扫描二维码关注公众号,回复: 14785541 查看本文章

猜你喜欢

转载自blog.csdn.net/A_yonga/article/details/127994515