SpringSecurity自定义认证失败处理器

自定义认证失败处理器

代码实现

1.实现AuthenticationFailureHandler接口

第一步:实现AuthenticationFailureHandler接口

@Component("customAuthenticationFailureHandler")
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler{
    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response, AuthenticationException exception){
        //以返回JSON数据为例
         Result result = Result.build(HttpStatus.UNAUTHORIZED.value(), exception.getMessage());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(result.toJsonString());
    }

}

2.配置SpringScurry

第二步:配置SpringScurry

@Autowired
private AuthenticationFailureHandler customAuthenticationFailureHandler;
@Override
//前后代码省略
protected void configure(HttpSecurity http) throws Exception {
    http
    //前后代码省略
    .failureHandler(customAuthenticationSuccessHandler)
}

跳转到上次访问页面

当我们要实现页面跳转时,我们只需要继承AuthenticationFailureHandler的实现类SimpleUrlAuthenticationFailureHandler然后调用父类的方法

@Component("customAuthenticationFailureHandler")
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
       super.setDefaultFailureUrl(securityProperties.getAuthentication().getLoginPage()+"?error");
       super.onAuthenticationFailure(request,response,exception);
       
    }
}
经验分享 程序员 微信小程序 职场和发展