Spring Security 完成登陆后一般需要一些自定义的处理,例如,记录登陆日志,初始化用户菜单等等
这里就需要自定义的 登陆成功处理了,Spring 提供了 AuthenticationSuccessHandler 接口,完成这个接口就可以了。 但是,修改到这里处理后,原先系统的自动转向处理就没有了,接口中应该怎么写,才可以保持原来的功能呢?
代码如下:
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication arg2) throws IOException, ServletException { logger.info("Success hanlder"); //这里加入需要的处理 String redirectUrl = "index"; //缺省的登陆成功页面 SavedRequest savedRequest = (SavedRequest) request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST"); if(savedRequest != null) { redirectUrl = savedRequest.getRedirectUrl(); request.getSession().removeAttribute("SPRING_SECURITY_SAVED_REQUEST"); } response.sendRedirect(redirectUrl); }
主要是读取Session中 SPRING_SECURITY_SAVED_REQUEST的值,获得原先的跳转页面。
当然 SecurityConfig 里面这样配置
@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { // @formatter:off @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() // .antMatchers("/css/**", "/index","/plug-in/**").permitAll() .antMatchers("/user/**","/blank","/ui_colors").hasRole("ADMIN").and().formLogin() .loginPage("/login").failureUrl("/login-error").successHandler(new SimpleLoginSuccessHandler()).and().rememberMe(); } // @formatter:on // @formatter:off @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("admin").password("123456") .roles("ADMIN"); } // @formatter:on }