问题
How in Spring Security can I set a RememberMe cookie url path, that differs from the context path?
Supposing my website's homepage url is (url rewrite):
https://www.mysuperspecialdomain.com
And that my login page has a url like this:
https://www.mysuperspecialdomain.com/shop/account/login
After succesful login the RememberMe cookie has the path /shop (visible in the browser, e.g. Chrome). This is the project's context path.
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.
回答1:
If you use Spring Security 4.1.0 or higher, you can configure the cookie domain, see RememberMeConfigurer#rememberMeCookieDomain:
The domain name within which the remember me cookie is visible.
but you can't change the context path.
So you have to implement your own RememberMeServices (you could create a sub class of an existing one) and add it with RememberMeConfigurer#rememberMeServices to your security configuration.
回答2:
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 https://stackoverflow.com/a/7047298/7095884):
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); } } }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) ...
来源:https://stackoverflow.com/questions/41015150/spring-security-how-can-i-set-a-rememberme-cookie-url-path-that-differs-from-t