我正在使用带有自定义注销成功处理程序的spring boot。我想在登录屏幕上打印自定义消息,具体取决于它们被注销的原因。
@Component
public class LogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
if(request.getParameter("emailchange") != null) {
setDefaultTargetUrl("/signin?m=Your%20email%20address%20has%20been%20changed,%20please%20re-login.");
}
else if(request.getParameter("passwordchange") != null) {
setDefaultTargetUrl("/signin?m=Your%20password%20has%20been%20changed,%20please%20re-login.");
}
else {
setDefaultTargetUrl("/signin?m=You%20have%20been%20logged%20out.");
}
super.onLogoutSuccess(request, response, authentication);
}
}
我的安全性配置如下:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/signin")
.loginProcessingUrl("/signin/authenticate")
.failureUrl("/signin?login_error=t")
.defaultSuccessUrl("/dashboard")
.permitAll()
.and()
.logout()
.logoutUrl("/signout")
.logoutSuccessHandler(logoutSuccessHandler)
.deleteCookies("JSESSIONID")
.permitAll()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.sessionAuthenticationStrategy(new RegisterSessionAuthenticationStrategy(sessionRegistry))
.and()
.rememberMe()
.key("myrememberkey")
.rememberMeServices(rememberMeServices)
.and()
.requestCache()
.requestCache(requestCache)
.and()
.httpBasic()
.disable()
;
}
<form id="logout-form" action="<c:url value="/signout"/>" method="POST"><input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/><a href="#" onclick="document.getElementById('logout-form').submit();"><i class="fa fa-power-off"></i> Logout</a></form>
当我使用POST注销时(我正在使用csrf),我的LogoutSuccessHandler被调用,而JSESSIONID cookie标头显示它应该被删除。这将返回302重定向,其中包含从LogoutSuccessHandler设置的正确URL。
然后浏览器尝试加载/签名?m = You%20have%20been%20logged%20out但它会重新发送 OLD Cookie,该Cookie应该在POST /注销的302响应中删除。这导致另一个重定向(因为我们发送的JSESSION cookie已经失效)然后我们丢失了我的漂亮消息。有关如何防止此行为或确保浏览器在302重定向上正确删除cookie以响应POST请求的任何想法?我已经测试了最新的Firefox和Chrome,行为也一样。