在反向代理后通过HTTPS提供服务时,会话cookie未标记为Secure
Session cookie not marked Secure when served over HTTPS behind reverse proxy
ID: security/session-cookie-secure-flag-missing-behind-proxy
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Nginx 1.25 | active | — | — | — |
| Apache 2.4 | active | — | — | — |
| HAProxy 2.8 | active | — | — | — |
根因分析
应用服务器只看到来自反向代理的HTTP(TLS在代理处终止),因此不会在会话cookie上设置Secure属性,导致cookie在纯HTTP下暴露于窃听风险。
English
The application server only sees HTTP from the reverse proxy (TLS termination at proxy) and therefore does not set the Secure attribute on session cookies, exposing them to interception over plain HTTP.
官方文档
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie解决方案
-
配置反向代理转发X-Forwarded-Proto头。对于Nginx:proxy_set_header X-Forwarded-Proto $scheme; 并在应用中信任代理,当此头为'https'时设置安全cookie。
-
在应用程序配置文件中设置'Secure'属性,例如在Django中:SESSION_COOKIE_SECURE = True,但仅在生产环境中。
-
使用代理级重写向Set-Cookie头添加Secure属性。对于Nginx,使用headers-more-nginx-module:more_set_headers 'Set-Cookie: $upstream_http_set_cookie; Secure'
无效尝试
常见但无效的做法:
-
50% 失败
Forcing HTTPS on the application server directly without configuring the proxy headers may cause redirect loops or break the proxy connection.
-
40% 失败
Removing the proxy and using direct TLS termination on the app server is often not feasible in existing infrastructure.
-
30% 失败
Simply setting the Secure flag unconditionally in code may break local development over HTTP.