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.