[英]How can I configure Spring Security to use custom AuthenticationManager implementation?
[英]In Spring Security how do I capture exceptions from a custom AuthenticationManager?
我正在將Crowd的Java集成到Spring Security中,這涉及將Crowds SimpleAuthenticationManager配置為身份驗證提供程序。 根據無法通過身份驗證的原因,當用戶無法通過身份驗證時,SimpleAuthenticationManager會引發多個異常。 我想知道在Spring Security中如何捕獲該異常並向客戶端返回JSON響應?
我嘗試添加AccessDeniedHandler,但是這會收到一個新異常,該異常沒有原始異常。
在谷歌搜索和搜索StackOverflow時,我錯過了這篇文章: Spring Security 3 http-basic authentication-success-handler
事實證明,正如其他問題/答案所指出的那樣,您需要擴展BasicAuthenticationFilter並實現onUnsuccessfulAuthentication()方法。 然后使用以下命令將其添加到您的安全配置中:
http.addFilter(new CustomBasicAuthenticationFilter(authenticationManagerBean()))
編輯實際上,似乎Spring仍在包裝異常,但是您可以得到一些更具體的異常,這很有幫助。
您可以使用@ControllerAdvice
注釋擴展ResponseEntityExceptionHandler
。 這將捕獲異常,您可以處理並發送自定義響應。 例:
@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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.