Sending GET request with Authentication headers using restTemplate

前端 未结 6 1454
执念已碎
执念已碎 2021-01-31 01:20

I need to retrieve a resources from my server by sending a GET request with the some Authorization headers using RestTemplate.

After going over the docs I noticed that

6条回答
  •  感动是毒
    2021-01-31 01:47

    A simple solution would be to configure static http headers needed for all calls in the bean configuration of the RestTemplate:

    @Configuration
    public class RestTemplateConfig {
    
        @Bean
        public RestTemplate getRestTemplate(@Value("${did-service.bearer-token}") String bearerToken) {
            RestTemplate restTemplate = new RestTemplate();
            restTemplate.getInterceptors().add((request, body, clientHttpRequestExecution) -> {
                HttpHeaders headers = request.getHeaders();
                if (!headers.containsKey("Authorization")) {
                    String token = bearerToken.toLowerCase().startsWith("bearer") ? bearerToken : "Bearer " + bearerToken;
                    request.getHeaders().add("Authorization", token);
                }
                return clientHttpRequestExecution.execute(request, body);
            });
            return restTemplate;
        }
    }
    

提交回复
热议问题