How to set proxy on spring oauth2 OAuth2AccessToken request or How to override OAuth2AccessTokenSupport restTemplate variable?
Another way to do this is by setting a custom AccessTokenProvider to your OAuth2RestTemplate. In the code sample below the SSL validation is bypassed :
@Configuration
public class ConfigLocal {
@Value("${https.proxyHost}")
private String proxyHost;
@Value("${https.proxyPort}")
private Integer proxyPort;
@Value("${https.proxyUser}")
private String proxyUser;
@Value("${https.proxyPassword}")
private String proxyPassword;
@Bean
public OAuth2RestTemplate oauth2RestTemplate(ClientCredentialsResourceDetails clientCredentialsResourceDetails)
throws KeyManagementException, KeyStoreException, NoSuchAlgorithmException {
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(clientCredentialsResourceDetails);
// Instanciate a new http client with proxy configuration, and bypass SSL Certificate verification
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyUser, proxyPassword));
HttpClientBuilder httpClientBuilder =
HttpClients.custom()
.setProxy(new HttpHost(proxyHost, proxyPort))
.setDefaultCredentialsProvider(credentialsProvider)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, (x509Certificates, s) -> true)
.build());
// requestFactory
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build());
ClientCredentialsAccessTokenProvider clientCredentialsAccessTokenProvider = new ClientCredentialsAccessTokenProvider();
clientCredentialsAccessTokenProvider.setRequestFactory(requestFactory);
// accessTokenProvider
AccessTokenProvider accessTokenProvider = new AccessTokenProviderChain(Arrays.<AccessTokenProvider> asList(
new AuthorizationCodeAccessTokenProvider(), new ImplicitAccessTokenProvider(),
new ResourceOwnerPasswordAccessTokenProvider(), clientCredentialsAccessTokenProvider));
restTemplate.setAccessTokenProvider(accessTokenProvider);
return restTemplate;
}
}