Thanks Dave~
HttpComponentsClientHttpRequestFactory works great with basic authentication.
I've overrrided AuthorizationCodeAccessTokenProvider and setted my restTemplate with HttpComponentsClientHttpRequestFactoryBasicAuth which supports auth caching for preemtive authentication.
sample code here:
Code:
public class MockAuthorizationCodeAccessTokenProvider extends AuthorizationCodeAccessTokenProvider {
private RestTemplate restTemplate;
private HttpComponentsClientHttpRequestFactoryBasicAuth requestFactory;
public MockAuthorizationCodeAccessTokenProvider() {
this.restTemplate = new RestTemplate();
HttpHost targetHost = new HttpHost("local-gdp.onlinegame.com", 80, "http");
DefaultHttpClient httpClient = new DefaultHttpClient();
BasicCredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(new AuthScope(targetHost, AuthScope.ANY_REALM, "basic"), new UsernamePasswordCredentials("mocksite", "secret"));
httpClient.setCredentialsProvider(provider);
AuthCache authCache = new BasicAuthCache();
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
BasicHttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
this.requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth(httpClient);
this.requestFactory.setHttpContext(localContext);
this.restTemplate.setRequestFactory(requestFactory);
this.restTemplate.setErrorHandler(getResponseErrorHandler());
}
@Override
protected OAuth2AccessToken retrieveToken(MultiValueMap<String, String> form, HttpHeaders headers,
OAuth2ProtectedResourceDetails resource) throws OAuth2AccessDeniedException {
try {
// Prepare headers and form before going into rest template call in case the URI is affected by the result
//authenticationHandler.authenticateTokenRequest(resource, form, headers);
return getRestTemplate().execute(getAccessTokenUri(resource, form), getHttpMethod(),
getRequestCallback(resource, form, headers), getResponseExtractor(), form.toSingleValueMap());
}
catch (OAuth2Exception oe) {
throw new OAuth2AccessDeniedException("Access token denied.", resource, oe);
}
catch (RestClientException rce) {
throw new OAuth2AccessDeniedException("Error requesting access token.", resource, rce);
}
}
@Override
protected RestTemplate getRestTemplate() {
return restTemplate;
}
}
you can notice that authenticationHandler.authenticateTokenRequest(res ource, form, headers); is commented, because it overwrites authentication header. but that'd be no problem, the credentials are same anyway.