What is ngx_http_auth_request_module?
ngx_http_auth_request_module
Module implementing authorization of clients based on the result of a subrequest. If the subrequest returns a 2xx response code, access is allowed. If it returns 401 or 403, access is denied with the appropriate error code. Any other response code returned by a subrequest is considered an error.
auth_request
The use is also subrequest
for subrequests.
ngx_http_auth_request_module module purpose
When we need to authenticate when accessing a resource, we can use Nginx
the http_auth_request_module
module to process it
ngx_http_auth_request_module使用
nginx configuration file
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 code
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;
}
}
Test mock authentication success
Browser access address:http://localhost:8082/private
Console prints:
Simulate authentication failure and throw an exception
Code changes:
Restart the project access test:
the error page of nginx is returned, and it can also be customized