How can I configure multiple OAuth2RestTemplates (via OAuth2ProtectedResourceDetails) using Spring Boot so that I can access multiple APIs. They are all configured in same tenant as we see with all configuration being the same except for the scopes.
I believe I did read you cannot have multiple scopes because each JWT token is resource specific but I cannot see examples of having multiple RestTemplates.
Thank you!
security:
oauth2:
client:
client-id: x
client-secret: y
user-authorization-uri: z
access-token-uri: a
scope: B
grant-type: client_credentials
client2:
client-id: x
client-secret: y
user-authorization-uri: z
access-token-uri: a
scope: Q
grant-type: client_credentials
@Bean(name="ngsWbRestTemplate")
public OAuth2RestTemplate buildNgsWbRestTemplate(
OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails
){
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(oAuth2ProtectedResourceDetails);
restTemplate.setMessageConverters(Collections.singletonList(new MappingJackson2HttpMessageConverter()));
restTemplate.getAccessToken().getValue();
return restTemplate;
}
@Bean(name="OdpRestTemplate")
public OAuth2RestTemplate buildOdpRestTemplate(
OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails,
@Value("#{propertyService.getValue('ODP_BASE_URI')}") String odpBaseUri
){
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(oAuth2ProtectedResourceDetails);
restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory(odpBaseUri));
restTemplate.setMessageConverters(Collections.singletonList(new MappingJackson2HttpMessageConverter()));
// test access token retrieval
restTemplate.getAccessToken().getValue();
return restTemplate;
}
I recently made a client that integrates the information of multiple providers who protect their APIs with the OAUth2 protocol. I used this dependency:
In the configuration.yml file you have to set all the properties needed for your client in order to get tokens from Authorization Servers.
In the main class you need to create a different bean for each resource server that you'd like to send requests with its corresponding access_token in the Authorization header.
Then you can autowire the OAuth2RestTemplate choosing the desired implementation with the @Qualifier annotation as shown below
Spring will refresh the tokens automatically when they expire and that's so cool.