我有三个角色,我想根据他们的角色在登录后将用户重定向到不同的页面。我知道这可以通过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方法并使用它。
答案 0 :(得分:9)
试试这个:Moving Spring Security To Java Config, where does authentication-success-handler-ref go?
上述帖子中的代码:
@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) {
}
}