0
我有一個Spring REST API,它提供了許多端點;他們需要使用基本http或JWT令牌進行身份驗證。我使用的也是@ControllerAdvice就象這樣:Spring REST API,攔截401需要完全驗證
@ControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
private Logger log = LogManager.getLogger();
@Inject
private MessageSource messageSource;
@ExceptionHandler(value = { RuntimeException.class, Exception.class })
public ResponseEntity<ErrorMessage> exceptionHandler(RuntimeException ex, Locale locale) {
ErrorMessage error = new ErrorMessage(ApiExceptionCodes.GENERIC_INTERNAL_SERVER_ERROR, messageSource.getMessage(
ApiExceptionCodes.GENERIC_INTERNAL_SERVER_ERROR + "", null, locale));
return new ResponseEntity<ErrorMessage>(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(value = { ApiException.class })
public ResponseEntity<ErrorMessage> handlerApiException(ApiException ex, Locale locale) {
ErrorMessage error = new ErrorMessage(ex.getCode(), ex.getMessage());
return new ResponseEntity<ErrorMessage>(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(value = { ApiRuntimeException.class })
public ResponseEntity<ErrorMessage> handlerApiRuntimeException(ApiRuntimeException ex, Locale locale) {
ErrorMessage error = new ErrorMessage(ex.getCode(), messageSource.getMessage(ex.getCode() + "", null, locale));
return new ResponseEntity<ErrorMessage>(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
我的一個端點是這樣的:
@ApiOperation(value = "Return Spring Principal object.", notes = "Return Spring Principal object. It contains several details of the logged-in user.")
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAnyRole('B2B','API')")
public ResponseEntity<?> user(Principal user) {
return ResponseEntity.ok(user);
}
總之,我在我的應用程序在全球捕獲的異常。除了我嘗試調用端點而沒有進行身份驗證之外,一切正常。在這種情況下,異常不是由我@ControllerAdvice攔截和用戶看到這個身體的反應:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Error 401 Full authentication is required to access this resource</title>
</head>
<body>
<h2>HTTP ERROR 401</h2>
<p>Problem accessing /aci/api/v1/tickets/chart. Reason:
<pre> Full authentication is required to access this resource</pre>
</p>
<hr>
<a href="http://eclipse.org/jetty">Powered by Jetty:// 9.3.9.v20160517</a>
<hr/>
</body>
</html>
我怎麼能在全球範圍還截獲此異常?請建議我採取最佳做法。