Spring boot provide RestTemplateBuilder for inter communicate between two services or we it used to call Rest Services. To more secure web services require basic authentication so RestTemplateBuilder provide simple ways to supply basic authentication details while calling services.

RestTemplateBuilder includes a number of useful methods that can be used to quickly configure a RestTemplate. For example, to add BASIC auth support you can use builder.basicAuthorization("user", "password").build().

Example of RestTemplate supply Basic Authentication:

In my example http://localhost:8080/secureAPI is a secure web service which require basic authentication that we has supply using builder.basicAuthorization("user", "password").build() method.

   @Autowired
   private RestTemplateBuilder restTemplateBuilder;
  
   public String callSecureService() {
       RestTemplate restTemplate = restTemplateBuilder.basicAuthorization("zone","mypassword").build();  // build using basic authentication details
       return restTemplate.getForObject("http://localhost:8080/secureAPI",String.class);          // call using basic authentication 
   }

secureAPI is Secure web service

Spring boot RestTemplate with Basic Authentication

Spring boot RestTemplate with Basic Authentication

References:

Spring boot RestTemplateBuilder document

Was this post helpful?

2 comments. Leave new

This was very helpful however I am having problems writing a unit test for it now. The code below return NullPointerException on restTemplateBuilder.basicAuthorization(AUTH_ID,AUTH_PASSWORD).build()
Any suggestion?

@Before
public void setup(){
when(restTemplateBuilder.basicAuthorization(AUTH_ID,AUTH_PASSWORD).build()).
thenReturn(restTemplate);
}

Thank you

Can you please tell me which value is null? restTemplateBuilder?

Leave a Reply

Your email address will not be published. Required fields are marked *