基于Spring MVC Java的配置中的AuthenticationSuccessHandler


问题内容

我有三个角色,我想根据用户的角色将用户登录后重定向到不同的页面。我知道这可以通过来完成AuthenticationSuccessHandler,但是在基于Java的配置中声明它时遇到了麻烦。

到目前为止,我已经做到了。

protected void configure(HttpSecurity http) throws Exception {

    http
    .authorizeRequests()                                                                
    .antMatchers("/resources/**", "/login").permitAll()                  
    .antMatchers("/admin/**").hasRole("USER")                           
    .and()

    .formLogin()
        .loginPage("/login")
        .defaultSuccessUrl("/")
        .successHandler(successHandler) //----- to handle user role
        .failureUrl("/loginfailed")             
        .permitAll()
        .and()

    .logout()
        .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
        .deleteCookies("JSESSIONID")
        .invalidateHttpSession( true )
        .and();                    
}

我的问题是在哪里声明 successHandler 以及如何在该类中对其进行自动布线,或者如何在此类中声明 successHandler
方法并使用它。


问题答案:

上面帖子中的代码:

@Override
protected void configure(HttpSecurity http) throws Exception {
http
    .authorizeRequests()
      .anyRequest().authenticated()
      .and()
    .formLogin()
      .loginPage("")
      .defaultSuccessUrl("/")
      .failureUrl("")
      .successHandler(//declare your bean here) 
      .and()
    .logout()
      .permitAll()
      .and()
  }

然后,在身份验证处理程序中,您可以应用所需的逻辑

public class MYSuccessHandler implements    AuthenticationSuccessHandler {


private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

@Override
public void onAuthenticationSuccess(HttpServletRequest request,
  HttpServletResponse response, Authentication authentication) throws IOException {
    handle(request, response, authentication);

}

protected void handle(HttpServletRequest request,
  // logic

    redirectStrategy.sendRedirect(request, response, targetUrl);
}

/** Builds the target URL according to the logic defined in the main class Javadoc. */
protected String determineTargetUrl(Authentication authentication) {
  }
   }

此处列出的教程http://www.baeldung.com/spring_redirect_after_login