我已经做了很多谷歌搜索,但找不到答案。我尝试在 war 中的 web.xml
文件中设置以下内容,但没有任何影响:
<session-config>
<session-timeout>60</session-timeout>
<cookie-config>
<http-only>true</http-only>
<secure>true</secure>
</cookie-config>
</session-config>
在 tomcat context.xml
文件中添加 useHttpOnly
可以将 cookie 限制为仅 http,但我仍然需要确保它们的安全。
最佳答案
您无需执行任何操作。只要启动 session 的请求是 https
,Tomcat 就会将 session cookie 标记为安全
。
我还查看是否有任何正式记录该事实的内容,但我找不到。但这至少是 Tomcat 6.0.32 及更高版本的行为。
以下是来自 org/apache/catalina/connector/Request.java
的代码,该代码在方法末尾检查请求是否安全,如果安全,则设置cookie 上的 secure
标志:
/**
* Configures the given JSESSIONID cookie.
*
* @param cookie The JSESSIONID cookie to be configured
*/
protected void configureSessionCookie(Cookie cookie) {
cookie.setMaxAge(-1);
Context ctxt = getContext();
String contextPath = null;
if (ctxt != null && !getConnector().getEmptySessionPath()) {
if (ctxt.getSessionCookiePath() != null) {
contextPath = ctxt.getSessionCookiePath();
} else {
contextPath = ctxt.getEncodedPath();
}
}
if ((contextPath != null) && (contextPath.length() > 0)) {
cookie.setPath(contextPath);
} else {
cookie.setPath("/");
}
if (ctxt != null && ctxt.getSessionCookieDomain() != null) {
cookie.setDomain(ctxt.getSessionCookieDomain());
}
if (isSecure()) {
cookie.setSecure(true);
}
}
更新:您可以使用过滤器等手动尝试自行设置。您可以查看示例 set 'secure' flag to JSESSION id cookie
关于security - 如何在 tomcat 6 中将 session cookie 标记为安全(仅限 https),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11767526/