简体   繁体   中英

Spring Boot : Token authentication(bearer) in request headers in rest api when token also comes from calling another api

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:

    public class TokenGeneration {
    private static String token = null;

    @Scheduled(15 minutes)
    public String fetchToken() {
        // api call which return token
        HttpEntity<model> response = restTemplate.exchange(uri, POST, entity, model.class);
        token = response.getBody().getAccessToken();
    }
 }

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.

Do i need to make TokenGeneration class singleton so that only one instance of this class is made throught application?

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 :

HttpHeaders headers = new HttpHeaders();
    headers.set(CpsConstant.AUTHORIZATION, CpsConstant.BEARER + token);

So i tried with this custom interceptor :

 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);
}

will add this interceptor in restTemplate in config file.

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 :

if(token == null){
//call token generation fetchToken method 
}
  1. It is the right approach
  2. Spring default scope is always singleton if not specified
  3. It is ok to use interceptor, but what if you want to call a API without a token?

Best approach to use two separate methods to send request with token and without token using a separate class

@Component
public class RestClient {

@Autowired
RestTemplate restTemplate;

public HttpHeaders getRequestHeaderBearer() {

HttpHeaders headers = new HttpHeaders();

headers.setContentType(MediaType.APPLICATION_JSON);
headers.add(HeaderParameters.AUTHORIZATION, HeaderParameters.BEARER + 
TokenGeneration.token);

return headers;

}

public HttpHeaders getRequestHeader() {

HttpHeaders headers = new HttpHeaders();

headers.setContentType(MediaType.APPLICATION_JSON);

return headers;

}

public <T> ResponseEntity<T> restExchangeBearer(String url, HttpMethod httpMethod,
    Class<T> classObj) {

return restTemplate.exchange(url, httpMethod,
    new HttpEntity<>("parameters", this.getRequestHeaderBearer()), classObj);

}

public <T> ResponseEntity<T> restExchange(String url, HttpMethod httpMethod,
    Class<T> classObj) {

return restTemplate.exchange(url, httpMethod,
    new HttpEntity<>("parameters", this.getRequestHeader()), classObj);

}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM