其他处理器
大约 1 分钟Spring全家桶SpringSecurity认证授权
认证成功处理器
实际上在UsernamePasswordAuthenticationFilter进行登录认证的时候,如果登录成功了是会调用AuthenticationSuccessHandler的方法进行认证成功后的处理的。AuthenticationSuccessHandler就是登录成功处理器。我们也可以自己去自定义成功处理器进行成功后的相应处理。
MySuccessHandler
@Component
public class MySuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        System.out.println("认证成功!!!");
    }
}
认证失败处理器
@Component
public class MyFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        System.out.println("认证失败");
    }
}
注销成功处理器
@Component
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        System.out.println("登出成功");
    }
}
配置处理器到SpringSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;
    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;
    @Autowired
    private MyLogoutSuccessHandler myLogoutSuccessHandler;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 开启表单登录验证(SpringSecurity自带的登录页面)
        http.formLogin()
                // 认证成功处理器
                .successHandler(authenticationSuccessHandler)
                // 认证失败处理器
                .failureHandler(authenticationFailureHandler);
        // 登出成功处理器
        http.logout().logoutSuccessHandler(myLogoutSuccessHandler);
        http.authorizeRequests().anyRequest().authenticated();
    }
}
测试
@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }
}
使用后台输出的密码,进行登录,用户名默认是user:

输入用户名和密码:

观察后台:

然后,访问默认的注销接口/logout:

观察后台:

再次访问登录接口,随便输一个密码,观察后台:
