OpenResty中SAML全局认证报错:auth request unexpected status:302
问题解决:Nginx auth_request 触发 302 错误导致 500 响应
问题背景
已实现单个URL的SAML认证,IDP重定向登录正常,但通过auth_request将认证适配所有API时,出现错误:auth request unexpected status: 302 while sending to client,最终返回500状态码。
原因分析
Nginx的auth_request模块对认证请求的返回状态有严格要求:仅接受**2xx(认证成功)或401/403(认证失败)**状态码。当前配置中,location /saml直接代理到IDP的SSO服务,而IDP返回了302重定向响应,这不符合auth_request的预期,因此触发500错误。
解决方案
1. 规范认证流程逻辑
避免直接将auth_request指向IDP的跳转地址,新增一个内部认证检查接口:由应用侧判断用户是否已完成SAML认证,已认证则返回200,未认证则返回401,再通过Nginx的error_page将401请求重定向到IDP完成登录。
2. 优化Nginx配置处理重定向
如果无法新增应用侧接口,可通过Nginx拦截IDP的302响应,转换为auth_request可识别的状态码,再触发重定向。
修改后的Nginx配置示例(推荐方案)
server { listen 0.0.0.0:8443 default ssl; # 省略SSL、基础配置等内容 auth_request /saml-auth-check; # 内部认证检查接口:仅允许Nginx内部调用 location /saml-auth-check { internal; proxy_pass http://localhost:8093/saml/check-auth; # 应用侧提供的认证检查接口 proxy_pass_request_body off; proxy_set_header Content-Length ""; proxy_set_header X-Original-URI $request_uri; } # 未认证时重定向到IDP error_page 401 = @saml-login; location @saml-login { return 302 http://172.19.167.213:9180/simplesaml/saml2/idp/SSOService.php?spentityid=https://172.19.167.213/; } location /enrollment/saml/callback { proxy_pass http://localhost:8093/saml/callback; return 302 https://172.19.167.213/; } }
关键说明
internal标记确保认证检查接口不对外暴露- 应用侧
/saml/check-auth接口需实现:验证用户是否有有效SAML会话,存在则返回200,不存在返回401 - 通过
error_page 401触发IDP重定向,符合auth_request的状态码要求
替代方案(无应用侧接口时使用)
server { listen 0.0.0.0:8443 default ssl; # 省略其他配置 auth_request /saml; location /saml { internal; proxy_pass http://172.19.167.213:9180/simplesaml/saml2/idp/SSOService.php?spentityid=https://172.19.167.213/; proxy_intercept_errors on; error_page 302 =401 @saml-redirect; } location @saml-redirect { return 302 $upstream_http_location; } location /enrollment/saml/callback { proxy_pass http://localhost:8093/saml/callback; return 302 https://172.19.167.213/; } }
内容的提问来源于stack exchange,提问作者Manu
相关产品推荐
相关产品推荐

