I want to authenticate NTLM using Rest template , can any one suggest the way ?
2 Answers
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);

- 1,019
- 1
- 11
- 25
-
This doesn’t seem to work. The 3rd argument in NTCredrntials constructor is called “workstation”. Not sure what will go in there. I just passed null. It throws 401 unauthorised when I do a restTemplate.exchange on the url which means the credentials are not recognised. The same setup works in postman. – saran3h Nov 09 '21 at 19:42
-
@saran3h As the code above states, you need to send the hostname of the machine doing the request. See: https://hc.apache.org/httpcomponents-client-4.5.x/current/httpclient/apidocs/org/apache/http/auth/NTCredentials.html#NTCredentials(java.lang.String,%20java.lang.String,%20java.lang.String,%20java.lang.String) – StaticBR Nov 11 '21 at 07:37
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.

- 903
- 10
- 17