We have a rest API that uses Spring OAuth2
. After the user is authenticated, all the JSON responses are in the following format:
{"code" : 12345, "data" : "..." }
But the JSON response for authentication failures is not inline with the above format, as that is handled by Spring.
For example in case of incorrect credentials, the clients get HTTP status code 400 with JSON response as follows:
{"error": "invalid_grant", "error_description": "Bad credentials" }
In case the user account is locked, the clients get HTTP status code 400 with JSON response as follows
{"error":"invalid_grant","error_description":"User account is locked"}
All of this is because Spring TokenEndpoint.handleException() is handling the exceptions associated with /oauth/token
I would like to change the JSON response for OAuth2 failures to follow the first format.
This is what I have tried so far with no success:
- Use ControllerAdvice with highest precendence order & use @ExceptionHandler as described here
- implementing OAuth2ExceptionRenderer as described here
- implement ExceptionMapper
- added a new ObjectMapper with extending StdSerializer. Although my objectmapper is initialized it is not being used for serializing the exceptions. Maybe because Spring is calling MappingJackson2HttpMessageConverter directly and there seems to be several instances of this class in my app.
Any help in any of the above approaches or a new one would be highly appreciated.
I haven't tried this approach as I cannot change the contextpath for the existing clients.