java Cookie http 仅适用于 Spring Security 和 servlet 2.5?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35421596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cookie http only with spring security and servlet 2.5?
提问by jpganz18
I want to make my cookie secure and http request only.
我只想让我的 cookie 安全和 http 请求。
Ive seen many post like thisand seem to work fine, but using configuration files and servlet +3.
我看过很多帖子像这样,似乎做工精细,但使用的配置文件和servlet +3。
What I basically want to do is to set my cookie http only and (if possible) ssl only as well.
我基本上想要做的是只设置我的 cookie http 和(如果可能)只设置 ssl。
So far I added this to my web.xml
到目前为止,我将此添加到我的 web.xml
<session-config>
<session-timeout>60</session-timeout>
<cookie-config>
<http-only>true</http-only>
</cookie-config>
<tracking-mode>COOKIE</tracking-mode>
</session-config>
doesnt do anything, as far as I was reading, I also have to configure my servlet.xml to enable this feature, but I dont know how...
什么都不做,就我阅读而言,我还必须配置我的 servlet.xml 以启用此功能,但我不知道如何...
Any idea how to do this?
知道如何做到这一点吗?
EDIT:
编辑:
Since I am using servlets 2.5 the xml configuration is not an option, maybe a filter?
由于我使用的是 servlets 2.5,因此 xml 配置不是一个选项,也许是一个过滤器?
回答by jakub.josef
I hate XML configuration, so i spend some time for find non-XML solution.
我讨厌 XML 配置,所以我花了一些时间来寻找非 XML 解决方案。
Since Spring Security 1.3 you can use
从 Spring Security 1.3 开始,您可以使用
server.session.cookie.http-only=true
server.session.cookie.secure=true
in your application.propertiesfile.
在您的application.properties文件中。
Maybe there is a way to set this using pure Java Configuration, but i can't find them.
也许有一种方法可以使用纯 Java 配置来设置它,但我找不到它们。
回答by Rick Pearce
We ran across this issue recently. I tried the property settings for http-only, which worked locally, but not when we deployed to our test env. It's possible there were some default settings in the env overriding those local settings. What worked was to set the properties in a Spring config file:
我们最近遇到了这个问题。我尝试了 http-only 的属性设置,它在本地工作,但在我们部署到我们的测试环境时没有。env 中可能有一些默认设置覆盖了这些本地设置。有效的是在 Spring 配置文件中设置属性:
@Bean
public ServletContextInitializer servletContextInitializer() {
return new ServletContextInitializer() {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.setSessionTrackingModes(Collections.singleton(SessionTrackingMode.COOKIE));
SessionCookieConfig sessionCookieConfig = servletContext.getSessionCookieConfig();
sessionCookieConfig.setHttpOnly(true);
sessionCookieConfig.setSecure(true);
}
};
}
回答by Dipak Prajapati
With the help of ServletContextListenerwe have control at servlet at tomcat startup and shutdown. So here on tomcat startup we are setting the configuration of httponly.
在ServletContextListener的帮助下,我们可以在 tomcat 启动和关闭时控制 servlet。所以这里在 tomcat 启动时我们设置了 httponly 的配置。
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public final class ContextListener implements ServletContextListener {
private ServletContext context = null;
@Override
public void contextDestroyed(ServletContextEvent event) {
this.context = null;
}
@Override
public void contextInitialized(ServletContextEvent event) {
this.context = event.getServletContext();
this.context.getSessionCookieConfig().setHttpOnly(true);
}
}
Abb beloww entry in web.xml
在 web.xml 中的 Abb 下面w 条目
<listener>
<description>contextListener</description>
<listener-class>
main.ContextListener
</listener-class>
</listener>
回答by Barett
The context.xml changes mentioned by javagc will only reconfigure your session cookie.
javagc 提到的 context.xml 更改只会重新配置您的会话 cookie。
To change all of your cookies, you have 2 options:
要更改所有 cookie,您有两种选择:
Option 1) Update your application code to add cookies using a more secure method. Example: https://stackoverflow.com/a/30488471/95674
选项 1) 更新您的应用程序代码以使用更安全的方法添加 cookie。示例:https: //stackoverflow.com/a/30488471/95674
Option 2) You can configure a servlet filter to change ALL (other) cookies coming through the system. Add these 2 classes into the appropriate package in your WAR. Then update your web.xml as detailed below.
选项 2) 您可以配置一个 servlet 过滤器来更改通过系统传入的所有(其他)cookie。将这 2 个类添加到 WAR 中的相应包中。然后更新您的 web.xml,如下详述。
There is a simpler example of Option 2 listed on the OWASP site, if you are willing to add a dependency on the OWASP libraries. That is located here: https://www.owasp.org/index.php/HttpOnly#Using_Java_to_Set_HttpOnly
如果您愿意添加对 OWASP 库的依赖,OWASP 站点上有一个更简单的选项 2 示例。位于此处:https: //www.owasp.org/index.php/HttpOnly#Using_Java_to_Set_HttpOnly
Response Wrapper
响应包装器
This adds the http only flag to all cookies on the wrapped response.
这会将 http only 标志添加到包装响应上的所有 cookie。
public class HttpOnlyResponseWrapper extends HttpServletResponseWrapper {
public HttpOnlyResponseWrapper(HttpServletResponse res) {
super(res);
}
public void addCookie(Cookie cookie) {
StringBuilder header = new StringBuilder();
if ((cookie.getName() != null) && (!cookie.getName().equals(""))) {
header.append(cookie.getName());
}
if (cookie.getValue() != null) {
// Empty values allowed for deleting cookie
header.append("=" + cookie.getValue());
}
if (cookie.getVersion() == 1) {
header.append(";Version=1");
if (cookie.getComment() != null) {
header.append(";Comment=\"" + cookie.getComment() + "\"");
}
if (cookie.getMaxAge() > -1) {
header.append(";Max-Age=" + cookie.getMaxAge());
}
} else {
if (cookie.getMaxAge() > -1) {
Date now = new Date();
now.setTime(now.getTime() + (1000L * cookie.getMaxAge()));
SimpleDateFormat cookieFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss zzz");
header.append(";Expires=" + cookieFormat.format(now));
}
}
if (cookie.getDomain() != null) {
header.append(";Domain=" + cookie.getDomain());
}
if (cookie.getPath() != null) {
header.append(";Path=" + cookie.getPath());
}
if (cookie.getSecure()) {
header.append(";Secure");
}
header.append(";httpOnly");
addHeader("Set-Cookie", header.toString());
}
}
Filter
筛选
This Filter wraps configured responses in the above wrapper.
此过滤器将配置的响应包装在上述包装器中。
package yourpackage;
@WebFilter(filterName = "HttpOnlyFilter", urlPatterns = {"/*"})
public class HttpOnlyFilter implements Filter {
private FilterConfig config;
@Override
public void destroy() {
this.config = null;
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpOnlyResponseWrapper hres = new HttpOnlyResponseWrapper((HttpServletResponse)res);
chain.doFilter(req, hres);
}
public FilterConfig getFilterConfig() {
return this.config;
}
@Override
public void init(FilterConfig config) throws ServletException {
this.config = config;
}
}
Adapted (WARNING: NOT an exact copy!) from source: http://sylvanvonstuppe.blogspot.com/2007/07/servlet-filter-for-httponly.html
改编(警告:不是精确的副本!)来自来源:http: //sylvanvonstuppe.blogspot.com/2007/07/servlet-filter-for-httponly.html
web.xml
网页.xml
One last detail: ONLY IF you have annotation scanning turned OFF in your system like this:
最后一个细节:仅当您在系统中关闭注释扫描时,如下所示:
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
version="2.5" ***metadata-complete="true"***>
</web-app>
Then you will need to manually configure the above Filter in your web.xml file, like this:
然后你需要在你的 web.xml 文件中手动配置上面的过滤器,像这样:
<filter>
<filter-name>HttpOnlyFilter
<filter-class>yourpackage.HttpOnlyFilter
</filter>
<filter-mapping>
<filter-name>HttpOnlyFilter
<url-pattern>/*
</filter-mapping>
If your app scans annotations (which is the default), the web.xml part is not necessary.
如果您的应用扫描注释(这是默认设置),则不需要 web.xml 部分。
回答by Danny Varela
I believe you are missing the security tag. Try adding:
我相信您缺少安全标签。尝试添加:
<secure>false</secure>