Otto
Otto

Reputation: 450

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

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

Thanks, Otto

Upvotes: 3

Views: 979

Answers (1)

Otto
Otto

Reputation: 450

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());
        }
    };
}

Upvotes: 2

Related Questions