title: Spring Boot : Token authentication(bearer) in request headers in rest api when token also comes from calling another api
body: <p>In my spring boot Application i have a scheduler which calls an API to generate token which expires in 15 min. Time of scheduler is also 15 min. please find below sample: </p>
  
  <pre><code>    public class TokenGeneration {
      private static String token = null;
  
      @Scheduled(15 minutes)
      public String fetchToken() {
          // api call which return token
          HttpEntity&lt;model&gt; response = restTemplate.exchange(uri, POST, entity, model.class);
          token = response.getBody().getAccessToken();
      }
   }
  </code></pre>
  
  <p>I stored token value in static variable from a non static method so that i can use this token variable wherever i want to use token value. is this right approach ? if not plz let me know how i can achieve this.</p>
  
  <p>Do i need to make TokenGeneration class singleton so that only one instance of this class is made throught application?</p>
  
  <p>Also i want to create an interceptor or filter in which i can set Authorization headers and token value so that each request will populate authorization header automatically, i don't want to set authorization header in each request like this :</p>
  
  <pre><code>HttpHeaders headers = new HttpHeaders();
      headers.set(CpsConstant.AUTHORIZATION, CpsConstant.BEARER + token);
  </code></pre>
  
  <p>So i tried with this custom interceptor :</p>
  
  <pre><code> public class RestTemplateInterceptor implements ClientHttpRequestInterceptor{
  
  @Override
  public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
  
       String token = TokenGeneration.token;
       request.getHeaders().add("Authorization", "Bearer " + token);    
       return execution.execute(request, body);
  }
  </code></pre>
  
  <p>will add this interceptor in restTemplate in config file.</p>
  
  <p>So is this right approach for both token generation as well as setting headers for each request or any improvements need to be done in this approach ?
  Me thinking of calling token generation method in interceptor in case of token is null like :</p>
  
  <pre><code>if(token == null){
  //call token generation fetchToken method 
  }
  </code></pre>