2

Spring Boot version 2.6.3 appears to no longer send the default JSON responses with 401 codes and some others responses.

@Override
public void commence(HttpServletRequest httpServletRequest,
                     HttpServletResponse httpServletResponse,
                     AuthenticationException e) throws IOException, ServletException {

    logger.error("Responding with unauthorized error. Message - {}", e.getMessage());
    httpServletstrong textResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());

}

The response will have the 401 code, but an empty body. Previously for version 2.5.5 the body will contain this JSON response.

{
"timestamp": "2022-01-28T14:14:02.736+00:00",
"status": 401,
"error": "Unauthorized",
"path": "/api/auth/signin"
}

I ended up temporarily replicating it manually like below, however I was wondering if the default responses could still be generated automatically. This applies to other responses also which I cannot as easily manually define the response messages for. Perhaps it was changed in the new versions, or a bug with Spring?

response.setContentType("application/json;charset=UTF-8");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("timestamp", LocalDateTime.now().toString());
jsonObject.addProperty("status",  response.getStatus());
jsonObject.addProperty("error", HttpStatus.UNAUTHORIZED.getReasonPhrase());
jsonObject.addProperty("message", "Error: Unauthorized");
jsonObject.addProperty("path", request.getServletPath());
response.getWriter().write(jsonObject.toString());

I did find this https://stackoverflow.com/a/62651683/7184439 which explains how to override.

Shahar
  • 23
  • 1
  • 5

1 Answers1

0

Followed the link from @Chin Huang and was able to essentially revert the behavior.

I added the following code as a workaround to the Spring Security Configurations and I now once again get the default error messages.

@Bean
static BeanFactoryPostProcessor removeErrorSecurityFilter() {
    return (beanFactory) -> 
        ((DefaultListableBeanFactory)beanFactory).removeBeanDefinition("errorPageSecurityInterceptor");
}

Additional method that worked to revert this behavior was to allow access to "/error" explicitly.

https://github.com/spring-projects/spring-boot/issues/28759#issuecomment-975408187

https://github.com/spring-projects/spring-boot/issues/28953

Error response body is empty in Spring Boot 2.6

Shahar
  • 23
  • 1
  • 5