Amine Hatim
Amine Hatim

Reputation: 247

Basic authentication once time for all

I developped a spring-boot application. When I need to do REST requests (POST, PUT...) I use every time basic authentication like that

HttpEntity<PostJql> httpEntity = new HttpEntity<PostJql>(post, jiraUtils.getHeader());
        ResponseEntity<IssueDataWrapper> response = restTemplate.exchange(urlJiraResponse, HttpMethod.POST, httpEntity, IssueDataWrapper.class);

Is there another way to do basic authentication once time in the application and then use RestTemplate or httpPost {Put/Delete...} without basic authentication ?

Best regards

Upvotes: 1

Views: 667

Answers (1)

slim
slim

Reputation: 41223

Yes. Configure your RestTemplate with a ClientHttpRequestFactory that does what you need.

You can just set it in the constructor:

  restTemplate = new RestTemplate(requestFactory);

... or you can make all of these things beans and let Spring wire it.

You could extend SimpleClientHttpRequestFactory, overriding createRequest():

 public class BasicAuthSimpleClientHttpRequestFactory 
        extends SimpleClientHttpRequestFactory {

     @Override
     public HttpClientRequest createRequest(URI uri, HttpMethod httpMethod) {
         HttpClientRequest request = super.createRequest(uri, httpMethod);
         HttpHeaders headers = request.getHeaders();
         headers.add(... your auth header ...);
         return request;
     }
 }

... or you could bring in Apache HttpComponents as a dependency and use an HttpComponentsClientHttpRequestFactory, and configure the underlying Apache HttpClient to do the authentication you need. Apache documents this in detail, but to get you started:

    BasicCredentialsProvider credentialsProvider = 
         new BasicCredentialsProvider();

    credentialsProvider.setCredentials(AuthScope.ANY, 
        new UsernamePasswordCredentials("user", "password"));

    HttpClient client = HttpClientBuilder.create()
        .setDefaultCredentialsProvider(credentialsProvider)
        .build();

    RestTemplate restTemplate = new RestTemplate(
        new HttpComponentsClientHttpRequestFactory(client));

In my experience it's worth bringing in Apache HttpComponents if you can -- it is more reliable and configurable than the HttpUrlConnection based HTTP client that RestTemplate otherwise uses by default. When your requirements broaden to things like other authentication methods, timeouts, retry strategies etc., you'll be glad you have an HttpClient to configure.

Upvotes: 2

Related Questions