问题
I want to authenticate NTLM using Rest template , can any one suggest the way ?
回答1:
this is what I did taking cues from here. Credits goes here only.
- Set up rest template to use
apache http client
->compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.5'
Updated my rest template bean to use httpclient -
RestTemplate restTemplate = new RestTemplate(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); restTemplate.setRequestFactory(requestFactory);
Then just do what the link here says. Add the
NtlmAuthenticator class
and do this just before your restTemplate call.NtlmAuthenticator authenticator = new NtlmAuthenticator(userName, password); Authenticator.setDefault(authenticator);
That's it. You are all set up.
回答2:
If anyone stumble upon this entry again, this is the builtin solution:
Ensure your project includes the org.apache.httpcomponents.httpclient
.
Then you can build your RestTemplate with this snippet:
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new NTCredentials(user, password, "source-host-name", "domain-name"));
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
来源:https://stackoverflow.com/questions/45811242/how-to-set-ntlm-authentication-in-rest-template-header-in-spring