How to set HTTP Header for OAuth2RestTemplate

妖精的绣舞 提交于 2019-12-05 16:10:42

The http headers for accessing the token in Oauth2Restemplate in case of Client credentials are set in below method of ClientCredentialsAccessTokenProvider (since grant type is client credentials)

public OAuth2AccessToken obtainAccessToken(OAuth2ProtectedResourceDetails details, AccessTokenRequest request)
        throws UserRedirectRequiredException, AccessDeniedException, 
OAuth2AccessDeniedException {

ClientCredentialsResourceDetails resource = (ClientCredentialsResourceDetails) details;
return retrieveToken(request, resource, getParametersForTokenRequest(resource), new HttpHeaders());

}

We can set the http headers by having new custom Access token provider for client credentials and modifying the method as follows:

public OAuth2AccessToken obtainAccessToken(OAuth2ProtectedResourceDetails details, AccessTokenRequest request)
        throws UserRedirectRequiredException, AccessDeniedException, OAuth2AccessDeniedException {

ClientCredentialsResourceDetails resource = (ClientCredentialsResourceDetails) details;

    HttpHeaders headers1 = new HttpHeaders();

    headers1.add("Content-Type", "application/x-www-form-urlencoded");

    return retrieveToken(request, resource, getParametersForTokenRequest(resource), headers1);

}

You can keep the class same as ClientCredentialsAccessTokenProvider and add just the header lines.

Last step will be to set this new class as access token in configuration of Oauth2RestTemplate.

oauth2RestTemplate.setAccessTokenProvider(new ClientCredentialsCustomAccessTokenProvider());

This worked for me!

Here's another variation on the answer just to override the default Accept Header interceptor using a Lambda expression:

@Bean
protected RestTemplate restTemplate() {
    return new RestTemplate() {

        @Override
        public <T> RequestCallback acceptHeaderRequestCallback(Class<T> responseType) {
            return request -> {
                request.getHeaders().setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
            };
        }

    };
}

If you are using Spring boot mention the authentication scheme as form, it will solve the issue.

security:
  oauth2:
    client:
      clientAuthenticationScheme: form
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!