I am trying to consume a REST endpoint by using the RestTemplate Library provided by the spring framework. The endpoint also demands a Bearer Access Token as its authorization header, which is only obtained as the response from a user authentication endpoint, which in turn expects an encoded Basic Auth in its Header.

This is the high-level implementation that I have done thus far.

HttpHeaders headers = new HttpHeaders();
    HttpEntity<String> entity = new HttpEntity<String>("parameters",headers);
    ResponseEntity<?> result = this.restClient.exchange(urlToConsume, HttpMethod.GET, entity, String.class);

The 'fetchAccessToken' Method is implemented as follows

HttpHeaders headers = new HttpHeaders();
    HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

    ResponseEntity<?> result = restClient.exchange(authUrl, HttpMethod.GET, entity, String.class);
    //And Thereby fetching 'access_token' from the successful fetch.

I Want to know whether there is any cleaner way to replicate the above task of dealing with multiple Rest calls to accomplish a single task. Also, I want to know whether I am missing out any essential validations from a security point of view.

  • 1
    \$\begingroup\$ Do you need to fetch the bearer token every time? Isn't it valid for some time after issuing, so you can cache it? \$\endgroup\$
    – TomG
    Commented Apr 2, 2019 at 17:26
  • \$\begingroup\$ @TomG Presently, the function determines whether or not call the Token Endpoint by checking whether the previous token has passed its expiry time. \$\endgroup\$
    – Nithin
    Commented Apr 2, 2019 at 18:20

1 Answer 1


You can have an interceptor on RestTemplate. It will be called for each request. You can have the access token logic within the interceptor. You can also implementing caching so that you do not fire two requests for each task. In case the token expires (401 response), you can regenerate the token

class MyInterceptor implements ClientHttpRequestInterceptor {
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution){
      HttpHeaders headers = request.getHeaders();
      ... response = execution.execute(request, body);
     // handle unauthorized request


RestTemplate restTemplate(MyInterceptor interceptor){
  RestTemplate restTemplate = new RestTemplate();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.