成功登录后未调用Spring Security successHandler-返回码302

时间:2019-01-15 17:47:47

标签: spring spring-security

成功登录后(用户被重定向到defaultSuccessUrl中定义的页面),返回状态码302。似乎未调用successHandler。我想获取状态码200。 使用UI可以很好地进行身份验证,但是对于REST API调用,我也需要它。 以下是代码段:

配置

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {

    http
    .csrf().disable()
    .exceptionHandling()
    .authenticationEntryPoint(restAuthenticationEntryPoint)
    .and()
    .authorizeRequests()
    .antMatchers("/console/**").hasRole("ADMIN").anyRequest()
    .authenticated()
    .and()
    .formLogin()
    .loginPage("/login.xhtml")
    .loginProcessingUrl("/login")
    .permitAll()
    .successHandler(mySuccessHandler)
    .failureUrl("/console")
    .failureHandler(new CustomAuthenticationFailureHandler())
    .and()
    .logout()
    .invalidateHttpSession(true)
    .deleteCookies("JSESSIONID")
    .permitAll();

    http.headers().frameOptions().disable();

    http.formLogin().defaultSuccessUrl("/jobs.xhtml", true);

    http.logout().logoutSuccessUrl("/login.xhtml");

}

MvcConfiguration

@Configuration
 public class MvcConfig implements WebMvcConfigurer {

public void addViewControllers(ViewControllerRegistry registry) {

    registry.addViewController("/login").setViewName("login.xhtml");
    registry.addViewController("/").setViewName("login.xhtml");
    registry.addViewController("/jobs").setViewName("jobs.xhtml");

}

successHandler

@Component
public class MySavedRequestAwareAuthenticationSuccessHandler extends 
SimpleUrlAuthenticationSuccessHandler {

private RequestCache requestCache = new HttpSessionRequestCache();

@Override
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws ServletException, IOException {
    final SavedRequest savedRequest = requestCache.getRequest(request, response);

    if (savedRequest == null) {
        clearAuthenticationAttributes(request);
        return;
    }
    final String targetUrlParameter = getTargetUrlParameter();
    if (isAlwaysUseDefaultTargetUrl() || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
        requestCache.removeRequest(request, response);
        clearAuthenticationAttributes(request);
        return;
    }

    clearAuthenticationAttributes(request);
}

public void setRequestCache(final RequestCache requestCache) {
    this.requestCache = requestCache;
}

}

0 个答案:

没有答案