Using OAuth2RestTemplate as Multiple Users

I am creating a system that regularly exports data on behalf of many users to an external system, with HTTP requests authenticated by OAuth2.

I was able to successfully contact the external service using Spring Security OAuth2, with OAuth2RestTemplate configured as follows:

@Configuration
@EnableOAuth2Client
public class ExternalServiceConfiguration {

    @Autowired
    private OAuth2ClientContext oauth2Context;

    @Bean
    public OAuth2ProtectedResourceDetails credentials() {

        ClientCredentialsResourceDetails details = new ClientCredentialsResourceDetails();
        details.setAccessTokenUri("https://external-service.example.com/OAuth/Token");
        details.setClientId("abcdefghijklmnopq");
        details.setClientSecret("123456789123456789123456789");
        details.setGrantType("client_credentials");

        return details;
    }

    @Bean
    public OAuth2RestTemplate externalServiceRestTemplate() {
        return new OAuth2RestTemplate(credentials(), oauth2Context);
    }
}

This works well, and I can introduce the OAuth2RestTemplate bean in my services:

@Autowired
@Qualifier("externalServiceRestTemplate")
private OAuth2RestTemplate restTemplate;

However, in my application, I have several users who need to configure their own client keys. In case it matters, I do this batch job, that is, it is done outside of the usual HTTP request, and sometimes in the same stream context.

, OAuth2ProtectedResourceDetails , , OAuth2RestTemplate. , , , , .

- OAuth2RestTemplate , ?

+4
1

, .

bean, RestTemplate :

@Repository
public class ExternalServiceRepository {

    private static ConcurrentHashMap<String, OAuth2RestTemplate> restTemplates = new ConcurrentHashMap<>();

    /**
     * Get a RestTemplate for a specific client based on it client secret id.
     * Create one if it hasn't been initialized yet.
     */
    public OAuth2RestTemplate restTemplate(String clientKey) {

        synchronized (restTemplates) {
            OAuth2RestTemplate restTemplate = restTemplates.get(clientKey);

            if (restTemplate == null) {
                ClientCredentialsResourceDetails details = new ClientCredentialsResourceDetails();
                details.setAccessTokenUri("https://external-service.example.com/OAuth/Token");
                details.setClientId("abcdefghijklmnopq");
                details.setClientSecret(clientKey);
                details.setGrantType("client_credentials");

                restTemplate = new OAuth2RestTemplate(details, new DefaultOAuth2ClientContext());
                restTemplates.put(clientKey, restTemplate);
            }

            return restTemplate;
        }
    }
}

@EnableOAuth2Client, OAuth2 HTTP, DefaultOAuth2ClientContext. , , (, , , ).

, , RestTemplate, restTemplate :

RestTemplate restTemplate =
    externalServiceRepository.restTemplate("123456789123456789123456789");
+2

Source: https://habr.com/ru/post/1659190/


All Articles