--- title: "使用NGINX的auth_request进行统一jwt鉴权 - 侯锐的思考与分享" source: "https://www.nosuchfield.com/2025/07/24/Using-NGINX-auth_request-for-unified-JWT-authentication/" author: - "[[Raymond]]" published: created: 2025-10-30 description: "

NGINX的auth_request模块提供了一种统一的认证机制,可以在NGINX层面进行JWT鉴权,而不需要在每个后端服务中重复实现认证逻辑。

首先我们定义一下nginx的配置,它的配置如下

flat
1
2
3
4
5
6
7
8
404 Not Found

Not Found

The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

~ curl http://localhost:8965/api/public/hello {"msg":"hello without auth"} ~ curl http://localhost:8965/api/hello Unauthorized% ``` 如上我们正确设置了Authorization之后就可以正常访问需要鉴权的接口了,但是去掉了Authorization之后需要鉴权的接口就会返回Unauthorized。此外还可以看到,不需要鉴权的接口,即使不添加鉴权配置也是可以正常访问的。