Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RestTemplate with Bearer Authorization

Is it possible to create with RestTemplateBuilder an instance of RestTemplate with just the bearer header and token?

I know i can use RestTemplate exchange and set inside the HttpEntity my headers but is it possible to do something like this:

public RestTemplate getRestTemplate(){
    RestTemplateBuilder builder = new RestTemplateBuilder();
    return builder.build().exchange().setBearerAuth("token here"); //this is not possible
}

Hope you understand what i want to do.

like image 578
svrdoljak Avatar asked Jun 16 '26 03:06

svrdoljak


2 Answers

As lilalinux pointed out in the comment - Authorization is the name of the header and Bearer + the token itself are the value.

@Bean(name = "myRestTemplate")
public RestTemplate collectCentRestTemplate(RestTemplateBuilder builder) {
    return builder.rootUri("some uri")
            .additionalInterceptors((ClientHttpRequestInterceptor) (request, body, execution) -> {
                request.getHeaders().add("Authorization", "Bearer " + token);
                return execution.execute(request, body);
            }).build();
}
like image 154
ksysha Avatar answered Jun 18 '26 16:06

ksysha


    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization" , "Bearer token");
    HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<(headers);

    ResponseEntity<Object> response = null;

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("url");
    try {
        response = restTemplate.exchange(builder.toUriString(),
                HttpMethod.GET,
                entity, Object.class);
    } catch (Exception e) {
        e.printStackTrace();
    }

You can try this one.

like image 28
logbasex Avatar answered Jun 18 '26 16:06

logbasex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!