Java Spring AuthenticationEntryPoint返回Tomcat HTML错误,而不是JSON

Java Spring AuthenticationEntryPoint返回Tomcat HTML错误,而不是JSON,java,spring,spring-security,Java,Spring,Spring Security,我正在使用Spring在一个更大的应用程序中公开API和API。访问authenticated()配置后面的端点时,我的应用程序会抛出一个丑陋的Tomcat HTML错误,原因是以下代码: @Component public class EntryPointUnauthorizedHandler implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest http

我正在使用Spring在一个更大的应用程序中公开API和API。访问authenticated()配置后面的端点时,我的应用程序会抛出一个丑陋的Tomcat HTML错误,原因是以下代码:

@Component
public class EntryPointUnauthorizedHandler implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
            AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access Denied");
    }
}
然而,由于这是一个API,我只想返回JSON,就像我的API的其余部分一样。对于正常的异常处理,我设置了以下
@ControllerAdvice

@ControllerAdvice
public class DefaultExceptionHandler extends ResponseEntityExceptionHandler {

    /**
     * Default internal BadCredentialsException handler. Respond with 401 Unauthorized
     */
    @ExceptionHandler(value = BadCredentialsException.class)
    public ResponseEntity<Object> handleBadCredentialsException(BadCredentialsException e, WebRequest request) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return handleExceptionInternal(e, null, headers, HttpStatus.UNAUTHORIZED, request);
    }

    /**
     * Fallback default exception handler. Respond with 500
     */
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<Object> handleFallbackException(Exception e, WebRequest request) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return handleExceptionInternal(e, null, headers, HttpStatus.INTERNAL_SERVER_ERROR, request);
    }

    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body,
            HttpHeaders headers, HttpStatus status, WebRequest request) {

        final ErrorResponse error = new ErrorResponse(status, ex.getMessage());

        if (HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) {
            request.setAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE, ex, WebRequest.SCOPE_REQUEST);
        }

        return new ResponseEntity<Object>(error, headers, status);
    }
}

如何确保我的
AuthenticationEntryPoint
只有一个请求和响应对象,而不是丑陋的Tomcat HTML页面返回类似的格式错误。

您可以根据需要更改
HttpServletResponse

看看:

编写手动JSON字符串或使用ObjectMapper感觉非常难看和粗糙。真的没有合适的方法吗?感觉好像我用错了弹簧。如果需要在此AuthenticationEntryPoint中再次定义异常处理,那么在1个位置定义异常处理有什么意义呢?spring安全过滤器在spring dispatcher servlet之前发生。所以我猜spring无法控制安全过滤器链上发生的异常。我不知道还有什么别的办法。可能是复制的
{
    "status": 401,
    "message": "Bad credentials"
}