Nginx ngx_http_auth_request_module模块鉴权【下】携带账号密码登录

优化上篇文章

点我查看上篇

本篇改动

  1. 增加账号密码进行登录认证

nginx配置文件

server {
    
    
        listen       8082;
        server_name  localhost;

        location /private {
    
    
            # 传递参数
            set $auth_request_uri "http://127.0.0.1:8002/auth/token?name=$arg_name&pwd=$arg_pwd";
            auth_request /auth;
            # 鉴权通过后的处理方式
            proxy_pass http://127.0.0.1:8002/auth/success;
        }

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

注意看:name=KaTeX parse error: Expected 'EOF', got '&' at position 9: arg_name&̲pwd=arg_pwd
$arg_name以及 $arg_pwd 参数。稍后有说明

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(@RequestParam(value = "name", required = false) String name,
                                     @RequestParam(value = "pwd", required = false) String pwd,
                                     HttpServerRequest request) {
    
    
        System.out.println("请求认证服务器接口" + LocalDateTime.now());
        System.out.println(String.format("用户名:%s,密码:%s", name, pwd));
        if ("pitewu".equals(name) && "123456".equals(pwd)) {
    
    
            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;
    }
}

浏览器测试

localhost:8082/private?name=pitewu&pwd=12345666

nginx配置文件中的$arg_name就是路径name的值哦

在这里插入图片描述
在这里插入图片描述

我们再把路径改为:localhost:8082/private?name=pitewu&pwd=123456

在这里插入图片描述

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/A_yonga/article/details/127996311
今日推荐