我使用Crowd的Java集成到Spring Security中,其中涉及将Crowds SimpleAuthenticationManager配置为身份验证提供程序。当用户无法根据无法进行身份验证的原因进行身份验证时,SimpleAuthenticationManager会引发多个异常。我在Spring Security中想知道如何捕获该异常并将JSON响应返回给客户端?
我已经尝试添加AccessDeniedHandler但是这会收到一个新的异常,它没有原始异常作为原因。
答案 0 :(得分:0)
在谷歌搜索和搜索StackOverflow时,我错过了这篇文章: Spring security 3 http-basic authentication-success-handler
事实证明,正如其他问题/答案所指出的,您需要扩展BasicAuthenticationFilter并实现onUnsuccessfulAuthentication()方法。然后使用以下命令将其添加到您的安全配置中:
http.addFilter(new CustomBasicAuthenticationFilter(authenticationManagerBean()))
编辑实际上看起来Spring现在还在包装异常,但是你可以得到一些稍微更具体的异常,这很有帮助。
答案 1 :(得分:-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);
}
}