ngx_http_auth_request_module是什么?
ngx_http_auth_request_module
模塊 實(shí)現(xiàn)了基于一子請(qǐng)求的結(jié)果的客戶端的授權(quán)。如果子請(qǐng)求返回2xx響應(yīng)碼,則允許訪問(wèn)。如果它返回401或403,則訪問(wèn)被拒絕并顯示相應(yīng)的錯(cuò)誤代碼。子請(qǐng)求返回的任何其他響應(yīng)代碼都被認(rèn)為是錯(cuò)誤的。auth_request
使用的也是subrequest
進(jìn)行子請(qǐng)求。
ngx_http_auth_request_module模塊用途
當(dāng)我們?cè)L問(wèn)一個(gè)資源需要進(jìn)行鑒權(quán)時(shí),可以使用Nginx
的http_auth_request_module
模塊進(jìn)行處理
ngx_http_auth_request_module使用
nginx配置文件
server {
listen 8082;
server_name localhost;
location /private {
auth_request /auth;
# 鑒權(quán)通過(guò)后的處理方式
proxy_pass http://127.0.0.1:8002/auth/success;
}
location = /auth {
# 鑒權(quán)服務(wù)器的地址
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: 認(rèn)證服務(wù)器
*/
@RestController
@RequestMapping("/auth")
public class NginxAuthRequestController {
@GetMapping("/token")
public Map<String, Object> token() {
System.out.println("請(qǐng)求認(rèn)證服務(wù)器接口" + LocalDateTime.now());
Map<String, Object> result = new HashMap<String, Object>();
result.put("code", 200);
result.put("msg", "成功");
return result;
// throw new RuntimeException("認(rèn)證失敗");
}
@GetMapping("/success")
public Map<String, Object> success() {
System.out.println("認(rèn)證成功" + LocalDateTime.now());
Map<String, Object> result = new HashMap<String, Object>();
result.put("code", 200);
result.put("msg", "成功");
return result;
}
}
測(cè)試模擬認(rèn)證成功
瀏覽器訪問(wèn)地址:http://localhost:8082/private
控制臺(tái)打?。?br>
模擬認(rèn)證失敗,拋出異常
代碼變動(dòng):文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-584773.html
重啟項(xiàng)目訪問(wèn)測(cè)試:
返回的是nginx的錯(cuò)誤頁(yè)面哦,也可以自定義處理文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-584773.html
到了這里,關(guān)于Nginx ngx_http_auth_request_module模塊鑒權(quán)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!