Guinaume
Guinaume

Reputation: 97

Spring security oauth2 modify response body connexion

For my application, i'm using Spring security to secure API Rest. For this i use an oauth2 system (with AuthorizationServerConfiguration, OAuth2SecurityConfiguration and ResourceServerConfiguration)

I don't find how to modify the body of my response connexion.

For moment, i have:

{
"access_token": "0d1dded8-3631-472a-ba63-89d67d133112",
"token_type": "bearer",
"refresh_token": "d9f4cc5d-748b-461f-b475-3bba95b512dc",
"expires_in": 29162,
"scope": "read write trust"
}

And i want something like that:

{
"errorLevel":"OK",
"errorMsg":"You are now connected",
"data": { // access_token, token_type... }
}

My first idea was to implement my accessTokenConverter and add it to the endpoints like that:

endpoints.accessTokenConverter(new CustomAccessTokenConverter());

But, he don't use my AccessTokenConverter.

So, how i can modify my response?

Upvotes: 0

Views: 1318

Answers (1)

SeaBiscuit
SeaBiscuit

Reputation: 2611

For newer versions of spring you can use ResponseBodyAdvice https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyAdvice.html to change the response.

Implementation goes something like this :

@ControllerAdvice
public class OauthReponseAdvice implements ResponseBodyAdvice<SomeResponseType> {
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
    return true;
}

@Override
public SomeResponseType beforeBodyWrite(SomeResponseType body, MethodParameter returnType, MediaType selectedContentType, Class<? extends
HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

     /// Modify body here
    return body;
   }
}

Upvotes: 4

Related Questions