Nginx通过auth_request将鉴权完全交由后端微服务处理:1.定义internal的/_auth子请求入口并透传关键头;2.全局启用auth_request并提取user/scopes上下文透传下游;3.显式关闭/login等豁免路径以防死循环;4.用error_page统一处理401/403跳转或返回。

直接在 Nginx 的 http 块或 server 块中配置 auth_request,就能把鉴权逻辑完全交给后端微服务——Nginx 不做任何校验,只负责转发请求、看状态码、传头信息、跳转错误页。
1. 定义内部鉴权子请求入口
必须用 internal 限制该 location 只能被 Nginx 自身调用,禁止外部直连:
location = /_auth { internal; proxy_pass https://auth-svc/oauth2/introspect;-
proxy_pass_request_body off;—— 大多数鉴权接口只读 header,关 body 避免超时或干扰 -
proxy_set_header Content-Length "";—— 清空长度头,配合关 body -
proxy_set_header X-Original-URI $request_uri;—— 让后端知道用户想访问哪条路径 -
proxy_set_header X-Original-Method $request_method;—— 区分 GET/POST 等操作权限 -
proxy_set_header Authorization $http_authorization;—— 显式透传原始 token(Nginx 默认不传) -
proxy_set_header Host auth-svc;—— 防止后端因 Host 不匹配拒绝请求
2. 全局启用并提取用户上下文
在 http 块顶部设默认行为,所有路径自动触发鉴权(例外路径再单独关掉):
-
auth_request /_auth;—— 所有未显式关闭的 location 都走这道检查 -
auth_request_set $user $upstream_http_x_user;—— 从认证服务响应头里提用户名 -
auth_request_set $scopes $upstream_http_x_scopes;—— 提权限范围,用于后续路由或 RBAC -
proxy_set_header X-User $user;—— 统一透传给所有后端,不用每个 location 单独写 proxy_set_header X-Scopes $scopes;
3. 明确豁免不需要鉴权的路径
登录页、静态资源、健康检查等必须显式关闭,否则形成死循环:
location = /login { auth_request off; }location = /callback { auth_request off; }location /assets/ { auth_request off; }location = /health { auth_request off; }location = /favicon.ico { auth_request off; }-
location / { try_files $uri /index.html; auth_request off; }—— SPA fallback 要放行
4. 错误响应由 Nginx 主动处理
别让 401 直接返回前端,避免白屏或报错;统一由 Nginx 跳转到登录页:
error_page 401 =302 https://auth.example.com/login?redirect_uri=$scheme://$host$request_uri;-
error_page 403 = @forbidden;—— 可配自定义拒绝页 location @forbidden { return 403 "Access denied"; }- 确保
/login和/callback已设auth_request off,闭环才成立


















