0

我正在将 Crowd 的 Java 集成到 Spring Security 中,这涉及将 Crowds SimpleAuthenticationManager配置为身份验证提供程序。当用户基于无法通过身份验证的原因而无法通过身份验证时,SimpleAuthenticationManager 会引发几个异常。我想知道在 Spring Security 中如何捕获该异常并将 JSON 响应返回给客户端?

我尝试添加一个 AccessDeniedHandler ,但是这会收到一个新异常,该异常没有原始异常作为原因。

4

2 回答 2

0

我在谷歌搜索和搜索 StackOverflow 时错过了这篇文章: Spring security 3 http-basic authentication-success-handler

事实证明,正如其他问题/答案所指出的那样,您需要扩展 BasicAuthenticationFilter 并实现 onUnsuccessfulAuthentication() 方法。然后将其添加到您的安全配置中:

http.addFilter(new CustomBasicAuthenticationFilter(authenticationManagerBean()))

编辑实际上,此时 Spring 似乎仍在包装异常,但是您可以获得一些更具体的异常,这很有帮助。

于 2018-05-04T15:01:16.760 回答
-1

ResponseEntityExceptionHandler您可以使用@ControllerAdvice注释进行扩展。这将捕获异常,您可以处理和发送自定义响应。例子:

@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(CustomExceptionHandler.class);

    public CustomExceptionHandler() {
    }

    // overriding an exception that already is been handled in ResponseEntityExceptionHandler
    @Override
    protected ResponseEntity<Object> handleMissingPathVariable(MissingPathVariableException ex,
            HttpHeaders headers, HttpStatus status, WebRequest request) {
        log.warn(ex.toString());

        final String parameter = ex.getParameter().getParameterName();
        final String detailMessage = ex.getMessage();
        final String message = "Parameter " + parameter + " is missing.";

        final ErrorMessageDTO result = new ErrorMessageDTO(HttpStatus.BAD_REQUEST, message, parameter, detailMessage, null);
        return ResponseEntity.badRequest().body(result);
    }

    // Custom handle to intercept BadCredentialsException
    @ExceptionHandler(BadCredentialsException.class)
    @ResponseBody
    ResponseEntity<Object> handleBadCredentialsException(HttpServletRequest req,
            BadCredentialsException ex) {
        log.warn(ex.toString());

        final ErrorMessageDTO result = new ErrorMessageDTO(HttpStatus.UNAUTHORIZED, ex.getMessage());
        return ResponseEntity.badRequest().body(result);
    }

}
于 2018-04-27T21:56:24.363 回答