配置 auth_request 子请求到 OAuth2 认证服务,验证后路由

解读

国内生产环境普遍把 Nginx 放在最前端做统一流量入口,OAuth2 认证服务(自研或基于 Spring Authorization Server、Keycloak、阿里 IDaaS 等)只负责签发 access_token。面试官想确认三件事:

  1. 能否用 auth_request 模块把“鉴权”与“业务”解耦,避免在 Nginx 里写复杂业务逻辑;
  2. 是否理解 OAuth2 的 302/authorization-code 流程与 Bearer Token 校验的差异,并针对“已登录”场景(token 已存在于 Cookie/Header)做子请求校验;
  3. 能否给出“鉴权失败 → 302 到登录页”、“鉴权成功 → 透传原始请求”的完整配置,并兼顾性能、缓存、异常降级、灰度发布等国内运维刚需。
    回答时切忌只贴配置,要说明每一步背后的机制、风险与可观测性方案,体现“能落地、能救火”的资深水平。

知识点

  1. auth_request 指令:Nginx 在内容阶段前发起内部子请求,子请求返回 2xx 则继续,返回 401/403 则中断,返回 302 不会自动跟随,需配合 error_page 处理。
  2. 内部 Location:以 @ 开头的 location 仅内部可见,避免外部直接访问鉴权接口。
  3. OAuth2 自校验端点:国内习惯在网关层做无状态校验,即把 access_token 送到 /oauth2/introspect 或 /oauth2/userinfo,返回 200 即合法,响应体可带回用户信息。
  4. 变量与映射:map 指令根据 Cookie/Authorization 构造 introspect 参数,避免 if 性能陷阱。
  5. 缓存与连接池:proxy_cache_path 缓存 200 响应,proxy_cache_key 包含 token 前 8 字节+过期时间,降低高并发下对认证服务的重复请求;upstream keepalive 复用连接。
  6. 灰度与降级:split_clients 按 token 尾号灰度到新版本认证服务;auth_request_set $auth_status 保存子请求状态,若认证服务超时(proxy_connect_timeout 1s)则返回 503,可配置 error_page 503 =200 /allow,实现“失败放通”或“本地缓存放行”。
  7. 安全细节:
    • 隐藏内部地址:proxy_hide_header X-Internal;
    • 防重放:token 绑定 jti 与 TTL;
    • 防伪造:introspect 接口仅接受内网 mTLS;
    • 日志审计:log_format 中记录 upstreamstatus、upstream_status、request_time、$http_x_request_id,方便与认证服务 traceId 串联。
  8. 热升级:auth_request 子请求走的是 upstream,升级认证服务时利用 Nginx 的 binary upgrade 零中断;若认证服务本身需蓝绿,可在 upstream 里切流。
  9. 合规:国内等保 2.0 要求“访问控制与身份鉴别”,需留存 6 个月以上日志,Nginx 侧需打开 requestbody与request_body 与 http_authorization 的日志,但要对 token 做脱敏(正则替换前 10 位)。

答案

生产级配置示例(基于 Nginx 1.24,OpenResty 同理):

# 1. 缓存区,用于缓存 introspect 结果
proxy_cache_path /var/cache/nginx/oauth2 levels=1:2 keys_zone=oauth2:10m inactive=10m max_size=1g;

# 2. 提取 token,优先读 Cookie,其次读 Authorization
map $http_cookie $token_cookie {
    "~*access_token=(?<t>[^;]+)" $t;
}
map $http_authorization $token_header {
    "~*Bearer (?<t>.*)" $t;
}
map $token_cookie$token_header $access_token {
    default $token_cookie;
    ""      $token_header;
}

# 3. 认证服务 upstream,支持 keepalive
upstream oauth2_backend {
    server 10.0.0.11:8080 max_fails=2 fail_timeout=5s;
    server 10.0.0.12:8080 max_fails=2 fail_timeout=5s;
    keepalive 100;
}

# 4. 业务 server
server {
    listen 80;
    server_name api.example.com;

    # 5. 所有业务请求先走 auth_request
    location / {
        auth_request /oauth2/introspect;
        auth_request_set $user_id $upstream_http_x_user_id;
        auth_request_set $auth_status $upstream_status;
        error_page 401 =302 https://login.example.com/oauth2/authorize?redirect_uri=$request_uri;
        error_page 403 = @deny;
        # 透传用户信息到后端
        proxy_set_header X-User-Id $user_id;
        proxy_pass http://backend;
    }

    # 6. 内部 introspect 子请求
    location = /oauth2/introspect {
        internal;
        proxy_cache oauth2;
        proxy_cache_key "$access_token";
        proxy_cache_valid 200 5m;          # token 剩余有效期一般 10m,这里缓存一半
        proxy_cache_lock on;
        proxy_cache_use_stale error timeout;
        proxy_ignore_headers Set-Cookie;   # 防止缓存被 Set-Cookie 污染
        proxy_method POST;
        proxy_set_body "token=$access_token";
        proxy_set_header Content-Type "application/x-www-form-urlencoded";
        proxy_pass http://oauth2_backend/oauth2/introspect;
        proxy_connect_timeout 1s;
        proxy_read_timeout 2s;
        # 隐藏内部地址
        proxy_hide_header X-Internal;
    }

    location @deny {
        return 403 '{"code":403,"msg":"Forbidden"}';
    }
}

关键解释

  1. 鉴权阶段完全无业务侵入,后端服务只需信任 X-User-Id 头。
  2. 缓存 5 分钟,把对认证服务的 QPS 降低 80% 以上;若 token 被主动吊销,认证服务需返回 401,Nginx 自动淘汰缓存。
  3. 认证服务超时 1 s 即失败,可快速触发降级策略(error_page 503 =200 /allow)或熔断。
  4. 灰度发布:在 upstream 里新增新版本节点,利用 split_clients 按 token 尾号分流,验证无误后全量切流。
  5. 日志:
    log_format main 'remoteaddr[remote_addr [time_local] "request"request" status request_time ' 'auth=auth_status user=useridtoken=′user_id token='{access_token:0:8}'****';
    既满足审计,又避免明文 token 泄露。

拓展思考

  1. 多租户场景:token 里包含 tenant_id,introspect 返回 200 的同时带回租户信息,Nginx 侧利用 map 指令把 tenant_id 映射到不同 upstream,实现“同一域名下按租户路由到不同 K8s 集群”。
  2. 边缘计算:在 CDN 边缘节点(阿里云 DCDN、腾讯云 ECDN)部署 Nginx+auth_request,introspect 回源到中心机房,利用 keepalive+TLS 会话复用降低 RT;若中心故障,边缘节点可降级为本地 JWT 公钥校验,实现“断网不断服”。
  3. 零信任演进:把 auth_request 子请求换成 Lua 脚本(access_by_lua_block),在 Nginx 侧做 JWT 本地验签 + 远程吊销列表(CRL/OCSP)混合校验,进一步降低延迟至 1 ms 内。
  4. 可观测性:把 authstatus、auth_status、user_id、$request_id 通过 syslog 送到 Loki,Grafana 面板实时展示“鉴权失败率 TOP10 用户”,方便安全运营及时封禁异常账号。
  5. 合规升级:等保 3.0 要求“国密算法”,可在 Nginx 侧编译 gmssl 模块,introspect 接口使用 SM2 双证双向 TLS,token 本身使用 SM4 加密,满足政务、金融云要求。