I want to authenticate NTLM using Rest template , can any one suggest the way ?
Now that everything is in place, the RestTemplate will be able to support the Basic Authentication scheme just by adding a BasicAuthorizationInterceptor: restTemplate. getInterceptors(). add( new BasicAuthorizationInterceptor("username", "password"));
Click down to “Local Computer Policy -> Computer Configuration -> Windows Settings -> Security Settings -> Local Policies -> Security Options. Find the policy “Network Security: LAN Manager authentication level”. Right click on this policy and choose “Properties”. Choose “Send NTLMv2 response only/refuse LM & NTLM”.
To enable basic authentication in RestTemplate for outgoing rest requests, we shall configure CredentialsProvider into HttpClient API. This HttpClient will be used by RestTemplate to send HTTP requests to backend rest apis. In this example, we are creating a Junit test which invokes a basic auth secured rest api.
Setting bearer token for a GET request RestTemplate restTemplate = new RestTemplate(); String customerAPIUrl = "http://localhost:9080/api/customer"; HttpHeaders headers = new HttpHeaders(); headers. set("Authorization", "Bearer " + accessToken); //accessToken can be the secret key you generate.
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);
this is what I did taking cues from here. Credits goes here only.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With