无论是 defaultSuccessUrl() 还是 successForwardUrl(),最终都是配置的 AuthenticationSuccessHandler 的实例,该接口类图如下:

image.png

也可以自定义 AuthenticationSuccessHandler,完成定制化功能:例如不跳转,直接给前端返回登录结果(前后端分离场景)前端自己处理:

    @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
       @Override
       protected void configure(HttpSecurity http) throws Exception {
           http.authorizeRequests()
                   .anyRequest().authenticated()
                   .and()
                   .formLogin()
                   .loginPage("/login.html")
                   .loginProcessingUrl("/doLogin")
                   .successHandler(new MyAuthenticationSuccessHandler())
                   .failureUrl("/login.html")
                   .usernameParameter("uname")
                   .passwordParameter("passwd")
                   .permitAll()
                   .and()
                   .csrf().disable();
       }
    }
    public class MyAuthenticationSuccessHandler implements
       AuthenticationSuccessHandler{
       @Override
       public void onAuthenticationSuccess(HttpServletRequest request,
                                                  HttpServletResponse response,
                                                  Authentication authentication)
                                                  throws IOException, ServletException {
           response.setContentType("application/json;charset=utf-8");
           Map<String, Object> resp = new HashMap<>();
           resp.put("status", 200);
           resp.put("msg", "登录成功!");
           ObjectMapper om = new ObjectMapper();
           String s = om.writeValueAsString(resp);
           response.getWriter().write(s);
       }
    }

defaultSuccessUrlsuccessForwardUrl 的流程差异