nginx授权验证

创建日期:2024-06-21
更新日期:2024-12-18

nginx授权验证

参考资料:https://nginx.org/en/docs/http/ngx_http_auth_request_module.html

nginx可以进行授权验证:

/auth返回200,正常访问;

/auth返回401,则所有请求都返回401。

nginx2自带ngx_http_auth_request_module模块,不需要根据参考资料上那样编译。

微信图片_20230901104012.png

参考代码

package com.liteng.springboottest.controller;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@RestController
@RequestMapping("/hello")
public class HelloController {
    @Resource
    HttpServletRequest request;

    @GetMapping("/allow")
    @ResponseStatus(HttpStatus.OK)
    public String allow() {
        Enumeration<String> headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            String key = headers.nextElement();
            System.out.println(key + ": " + request.getHeader(key));
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getName() + ": " + cookie.getValue());
            }
        } else {
            System.out.println("cookie is null");
        }
        return "";
    }

    @GetMapping("/not-allow")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public String notAllow() {
        Enumeration<String> headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            String key = headers.nextElement();
            System.out.println(key + ": " + request.getHeader(key));
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getName() + ": " + cookie.getValue());
            }
        } else {
            System.out.println("cookie is null");
        }
        return "";
    }
}