0

I have implemented Oauth2 client in spring boot

public RestTemplate oAuthRestTemplate() {
    ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails();
    resourceDetails.setId("1");
    resourceDetails.setClientId(clientId);
    resourceDetails.setClientSecret(clientSecret);
    resourceDetails.setAccessTokenUri(accessTokenUrl);
    resourceDetails.setTokenName("accessToken");
    resourceDetails.setClientAuthenticationScheme(AuthenticationScheme.form);
    OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails, new DefaultOAuth2ClientContext());
    return restTemplate;
}

We I run the code, request body for token is as client_id & client_secret (by default)

Can we send is custome manner. like I want to send it as clientId & clientSecret.

Note: Class is annotated with @EnableOAuth2Client

prasingh
  • 452
  • 4
  • 18

1 Answers1

0

The names 'client_id' and 'client_secret' are specified by OAuth 2 So there is normally no need to change these.

However, Spring uses org.springframework.security.oauth2.client.token.auth.DefaultClientAuthenticationHandler

to post the client_id and client_secret. There you can see the field names are hardcoded :

form.set("client_id", resource.getClientId());
                if (StringUtils.hasText(clientSecret)) {
                    form.set("client_secret", clientSecret);
                }

You could try to subclass DefaultClientAuthenticationHandler, and use your own field names. But as it is created with 'new' in OAuth2AccessTokenSupport, you would need to subclass this also, and so on......

This can be tricky, a better way may be to add a org.springframework.http.client.ClientHttpRequestInterceptor at the org.springframework.security.oauth2.client.OAuth2RestTemplate

Create a class that implements ClientHttpRequestInterceptor, in its method org.springframework.http.client.ClientHttpRequestInterceptor#intercept you need to create a new request using the provided body of type byte[]. Convert it to a String, replace the field names, create a new request using it and proceed as described in the javadoc of the intercept() method.

To register the interceptor, create a spring bean of type OAuth2RestTemplate and register the interceptor there like

@Bean
OAuth2RestTemplate oAuth2RestTemplate(){
OAuth2RestTemplate template=new OAuth2RestTemplate;

ClientHttpRequestInterceptor interceptor= new ... //create your  interceptor here
template.setInterceptors(Arrays.asList(interceptor));

return template;
}
Community
  • 1
  • 1