Search code examples
javaspringspring-bootspring-oauth2

Changing Json return format of Spring OAuth2


while consolidating our json responses, I tried to change the spring oauth2 json response to our format.

From

{
  "error": "invalid_token",
  "error_description": "Invalid access token: undefined"
}

To

{
  "status" : 401,
  "error_code": "invalid_token",
  "description": "Invalid access token: undefined"
}

I've debugged and found several points which probably relevant, but I have trouble bring everything together.

These were my approaches

  • The response is written here OAuth2ExceptionJackson2Serializer, but I don't know how to exchange that serializer within spring
  • I found the WebResponseExceptionTranslator. But from my understanding, it doesn't allow to set a json body there
  • The json body is written by DefaultOAuth2ExceptionRenderer, but I couldn't manage to set that. I only found how to set the ExceptionTranslator, by setting it in AuthorizationServerEndpointsConfigurer. But it doesn't allow to set the renderer
  • The documentation talks about setting an HttpMessageConverter, I didn't figure out how to do that.

Long story short, I'm new to Spring and I really would appreciate some guidance on how to modify the repsonse.

Thanks, Otto


Solution

  • Found the solution, register the WebResponseExceptionTranslator:

        @Bean
    public WebResponseExceptionTranslator webResponseExceptionTranslator() {
        return new DefaultWebResponseExceptionTranslator() {
            @Override
            public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
                ResponseEntity<OAuth2Exception> responseEntity = super.translate(e);
                OAuth2Exception body = responseEntity.getBody();
                HttpHeaders headers = new HttpHeaders();
                headers.setAll(responseEntity.getHeaders().toSingleValueMap());
    
               // translate the exception
    
                return new ResponseEntity<>(body, headers, responseEntity.getStatusCode());
            }
        };
    }