在spring security 的config类型中配置.defaultSuccessUrl("/path")失败,如果登陆前有默认登陆路径的话登录成功后依旧跳转为登录前的路径,而没有按照我们设置中的.defaultSuccessUrl进行跳转;
其中设置代码如下
public final T defaultSuccessUrl(String defaultSuccessUrl, boolean alwaysUse) {
SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler();
handler.setDefaultTargetUrl(defaultSuccessUrl);
handler.setAlwaysUseDefaultTargetUrl(alwaysUse);
return this.successHandler(handler);
}
这个时候spring中是把路径设置到SavedRequestAwareAuthenticationSuccessHandler 类的defaultTargetUrl属性中;
再看登录成功后的处理类。
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
SavedRequest savedRequest = this.requestCache.getRequest(request, response);
if (savedRequest == null) {
super.onAuthenticationSuccess(request, response, authentication);
} else {
String targetUrlParameter = this.getTargetUrlParameter();
if (!this.isAlwaysUseDefaultTargetUrl() && (targetUrlParameter == null || !StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
this.clearAuthenticationAttributes(request);
String targetUrl = savedRequest.getRedirectUrl();
this.logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
this.getRedirectStrategy().sendRedirect(request, response, targetUrl);
} else {
this.requestCache.removeRequest(request, response);
super.onAuthenticationSuccess(request, response, authentication);
}
}
}
String targetUrlParameter = this.getTargetUrlParameter();
该代码中取到的跳转路径取值的属性不是我们设置的defaultTargetUrl所以没法生效;
如果需要强制指定登陆之后跳转的路径,需要重新设置一个AuthenticationSuccessHandler处理类,在配置类中设置以下代码可以强制指定登陆成功后的跳转路径.
// 强制指定登陆成功后跳转的路径
.successHandler(new ForwardAuthenticationSuccessHandler("/loginStatus?status=true"))
protected void configure(HttpSecurity http) throws Exception {
http.
authorizeRequests()
// 设置静态的资源允许所有访问
.antMatchers("/static/base/**").permitAll()
// 其他所有资源都需要登陆后才能访问
.anyRequest().authenticated()
// 设置默认登陆页面/login
.and().formLogin().loginPage("/login")
// 强制指定登陆成功后跳转的路劲
.successHandler(new ForwardAuthenticationSuccessHandler("/loginStatus?status=true"))
.failureUrl("/loginStatus?status=false")
.permitAll()
// 设置缓存,默认2周有效
.and().rememberMe().tokenValiditySeconds(1209600).key("mykey")
// 设置登出的路径和登出成功后访问的路径
.and().logout().logoutUrl("/loginOut").logoutSuccessUrl("/login").permitAll()
// 金庸crsf
.and().csrf().disable()
;
}