Spring Security - 身份验证失败的自定义处理程序:凭据错误

时间:2018-04-18 06:42:20

标签: java json spring-security

我已经在我的Spring安全应用程序中实现了这些自定义处理程序

  • AuthenticationSuccessHandler SimpleUrlAuthenticationSuccessHandler

  • AuthenticationFailureHandler SimpleUrlAuthenticationFailureHandler

  • 的AuthenticationEntryPoint

所以我可以按照我的要求获得JSON响应。

如果成功登录,我将获得有效的JSON响应,因为它通过我的自定义 AuthenticationSuccessHandler ,但如果凭据无效,它会给我一个 HTTP状态401 - 身份验证失败:凭据错误以及默认的HTML错误页面。

我想要一个JSON错误响应,而不是默认的HTML页面。 我需要实现其他任何处理程序吗?如果有,那么如何在config方法中配置它?

这是我的Spring Security配置方法:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers("/", "/list").access("hasRole('USER') or hasRole('ADMIN') or hasRole('DBA')")
            .antMatchers("/delete-user-*").access("hasRole('ADMIN')")
            .antMatchers("/edit-user-*").access("hasRole('ADMIN') or hasRole('DBA')")
            .and()
        .httpBasic()
            .authenticationEntryPoint(authenticationEntryPoint)
            .and()
        .formLogin()
            .loginProcessingUrl("/login")
            .usernameParameter("ssoId")
            .passwordParameter("password")
            .successHandler(authenticationSuccessHandler)
            .failureHandler(authenticationFailureHandler)
            .and()
        .rememberMe()
            .rememberMeParameter("remember-me")
            .tokenRepository(tokenRepository)
            .tokenValiditySeconds(86400)
            .and()
        .csrf()
            .disable()
        .exceptionHandling()
            .authenticationEntryPoint(authenticationEntryPoint)
            .accessDeniedHandler(accessDeniedHandler);
}

这是我的 CustomAuthenticationFailureHandler

@Component
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException exception) throws IOException, ServletException {

        response.setStatus(HttpStatus.BAD_REQUEST.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        JSONObject jsonResponse = new JSONObject();
        jsonResponse.put("error", true);
        jsonResponse.put("message", "Invalid credentials");
        response.getWriter().append(jsonResponse.toString());

        super.onAuthenticationFailure(request, response, exception);
    }
}

我尝试了很多东西,但直到现在一切都没有。

0 个答案:

没有答案