自定义认证失败处理器

代码实现

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);
       
    }
}
Logo

脑启社区是一个专注类脑智能领域的开发者社区。欢迎加入社区,共建类脑智能生态。社区为开发者提供了丰富的开源类脑工具软件、类脑算法模型及数据集、类脑知识库、类脑技术培训课程以及类脑应用案例等资源。

更多推荐