1 回答

TA貢獻1847條經驗 獲得超11個贊
假設您有這樣的 WebSecurity 配置。你只需要添加一個successHandler
@Configuration
@EnableWebSecurity
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
? ? @Autowired
? ? private SimpleAuthenticationSuccessHandler successHandler;
? ? @Bean("authenticationManager")
? ? @Override
? ? public AuthenticationManager authenticationManagerBean() throws Exception {
? ? ? ? ? ? return super.authenticationManagerBean();
? ? }
? ? @Autowired
? ? public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
? ? ? ? // @formatter:off
? ? ? ? auth.inMemoryAuthentication()
? ? ? ? ? ? .withUser("user1").password("{noop}user1Pass").roles("USER")
? ? ? ? ? ? .and()
? ? ? ? ? ? .withUser("admin1").password("{noop}admin1Pass").roles("ADMIN");
? ? ? ? // @formatter:on
? ? }
? ? @Override
? ? protected void configure(final HttpSecurity http) throws Exception {
? ? ? ? http.authorizeRequests()
? ? ? ? ? ? .antMatchers("/anonymous*").anonymous()
? ? ? ? ? ? .antMatchers("/login*").permitAll()
? ? ? ? ? ? .anyRequest().authenticated()
? ? ? ? ? ? .and()
? ? ? ? ? ? .formLogin()
? ? ? ? ? ? .loginPage("/login.html")
? ? ? ? ? ? .loginProcessingUrl("/login")
? ? ? ? ? ? .successHandler(successHandler)
? ? ? ? ? ? // ...? ? ? ??
? ? }
}
SimpleAuthenticationSuccessHandler 類
// Change onAuthenticationSuccess logic as per your requirement
@Component
public class SimpleAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
? ? private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
? ? @Override
? ? public void onAuthenticationSuccess(HttpServletRequest arg0, HttpServletResponse arg1, Authentication authentication)
? ? ? ? ? ? throws IOException, ServletException {
? ? ? ? redirectStrategy.sendRedirect(arg0, arg1, "/home");
? ? ? ? /*
? ? ? ? Collectionextends GrantedAuthority> authorities = authentication.getAuthorities();
? ? ? ? authorities.forEach(authority -> {
? ? ? ? ? ? if(authority.getAuthority().equals("ROLE_USER")) {
? ? ? ? ? ? ? ? try {
? ? ? ? ? ? ? ? ? ? redirectStrategy.sendRedirect(arg0, arg1, "/user");
? ? ? ? ? ? ? ? } catch (Exception e) {
? ? ? ? ? ? ? ? ? ? // TODO Auto-generated catch block
? ? ? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? } else if(authority.getAuthority().equals("ROLE_ADMIN")) {
? ? ? ? ? ? ? ? try {
? ? ? ? ? ? ? ? ? ? redirectStrategy.sendRedirect(arg0, arg1, "/admin");
? ? ? ? ? ? ? ? } catch (Exception e) {
? ? ? ? ? ? ? ? ? ? // TODO Auto-generated catch block
? ? ? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? throw new IllegalStateException();
? ? ? ? ? ? }
? ? ? ? });
? ? ? ? */
? ? }
}
這會將您的調用重定向到"/home",控制器將進一步負責加載您的對象。
添加回答
舉報