Spring REST API,拦截401需要完全身份验证

时间:2017-04-13 17:55:24

标签: java spring spring-mvc

我有一个提供许多端点的Spring REST API;他们需要使用Basic http或JWT令牌进行身份验证。我正在使用@ControllerAdvice:

@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>

我怎么能全局拦截这个例外?请建议我这样做的最佳做法。

1 个答案:

答案 0 :(得分:2)

对于Basic安全性,您可以扩展org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint并覆盖begin方法以返回自定义响应,例如:

 @Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
    response.addHeader("your_custom_header", "some_value");
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    PrintWriter writer = response.getWriter();
    writer.println("HTTP Status 401 - " + authException.getMessage());
}