Spring Security:如何设置一个与上下文路径不同的RememberMe Cookie网址路径? [英] Spring Security: How can I set a RememberMe cookie url path, that differs from the context path?
问题描述
如何在Spring Security中设置一个与上下文路径不同的RememberMe Cookie网址路径?
How in Spring Security can I set a RememberMe cookie url path, that differs from the context path?
假设我的网站的首页网址是(url rewrite) / p>
Supposing my website's homepage url is (url rewrite):
https://www.mysuperspecialdomain.com
而且我的登录页面有这样的URL:
And that my login page has a url like this:
https://www.mysuperspecialdomain.com/shop/account/login
成功登录后,RememberMe Cookie的路径 / shop
(在浏览器中显示,例如Chrome)。这是项目的上下文路径。
After succesful login the RememberMe cookie has the path /shop
(visible in the browser, e.g. Chrome). This is the project's context path.
这导致的情况,当我去我的主页,RememberMe不是登录。只有当我导航到url,以 https://www.myspecialdomain.com/shop
开头。
This leads to the situation, that when I'm going to my homepage, RememberMe is not logging in. Only when I navigate to a url, that starts with https://www.myspecialdomain.com/shop
it's doing it.
推荐答案
我已经找到了一个解决我自己的问题 - 通过 HttpServletResponseWrapper
可以完成对RememberMe-cookie路径的操作。这是解决方案(基于此答案 http://stackoverflow.com/a/7047298/7095884 ): p>
I've found a solution to my own question - manipulation of the path of the RememberMe-cookie can be done via an HttpServletResponseWrapper
. This is the solution (based on this answer http://stackoverflow.com/a/7047298/7095884):
-
定义HttpServletResponseWrapper:
Define an HttpServletResponseWrapper:
public class RememberMeCookieResponseWrapper extends HttpServletResponseWrapper {
public RememberMeCookieResponseWrapper(HttpServletResponse response) {
super(response);
}
@Override
public void addCookie(Cookie cookie) {
if (cookie.getName().equals("shop")) {
cookie.setPath("/");
}
super.addCookie(cookie);
}
}
定义一个过滤器,响应与刚才定义的包装:
Define a filter, that wraps the servlet response with the just defined wrapper:
public class RememberMeCookieFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (response instanceof HttpServletResponse) {
HttpServletResponse newResponse =
new RememberMeCookieResponseWrapper((HttpServletResponse)response);
chain.doFilter(request, newResponse);
}
}
}
到Spring Filter Chain前面的认证部分:
Add this filter to the Spring Filter Chain in front of the authentication part:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(new RememberMeCookieFilter(), UsernamePasswordAuthenticationFilter.class)
...
这篇关于Spring Security:如何设置一个与上下文路径不同的RememberMe Cookie网址路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!