RestTemplate with Bearer Authorization
Asked Answered
D

6

7

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.

Dedans answered 27/1, 2020 at 10:15 Comment(0)
V
6

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();
}
Vandalize answered 4/2, 2021 at 12:7 Comment(1)
Additionally, like in linalinux's comment, there should be a space after "Bearer". i.e. "Bearer " + tokenCollegiate
C
4
    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.

Canny answered 15/1, 2021 at 11:48 Comment(1)
new HttpEntity<(headers); ← missing >Alkalimeter
V
3

You can use interceptors to inject the token to the request headers like so

    @Bean(name = "myRestTemplate")
    public RestTemplate someRestTemplate(RestTemplateBuilder builder) {
        return builder.rootUri("some uri")
                .additionalInterceptors((ClientHttpRequestInterceptor) (request, body, execution) -> {
                    request.getHeaders().add("Bearer", "token");
                    return execution.execute(request, body);
                }).build();
    }

And from your app, you can simply use it like this:

    @Autowired
    @Qualifier("myRestTemplate")
    private RestTemplate restTemplate;

Keep in mind you can still use the restTemplate object as usual, setting headers and etc, but the Bearer header will always be overridden with "token" because the interceptors apply right before the request is made.

Veratridine answered 27/1, 2020 at 10:25 Comment(3)
When i call this RestTemplate, can i still add more headers and my body like usual?Dedans
@svrdoljak, yes, but the Bearer header will always be overrideVeratridine
The header should probably be: request.getHeaders().add("Authorization", "Bearer " + token), i.e. Bearer in the value part before the token and "Authorization" as the name of the header.Eggers
A
0

No, it was suggested and declined (Provide convenience methods for Headers in RestTemplateBuilder)

I think the easiest way at the moment is to do something like this:

RequestEntity<Void> request = RequestEntity.post(url)
    .accept(MediaType.APPLICATION_JSON).header("foo", "bar").build();
restTemplate.exchange(request, String.class);

I'm inclined to agree with @wilkinsona that adding extra convince methods might not as useful as the current basicAuthorization method. That one is quite common, and when it was added was super painful to code yourself (it's now easier since Spring 4.3.1 added the BasicAuthorizationInterceptor class).

We need to balance the convenience of any new convenience methods against the complexity of having too many ways to do the same thing. Since it's relatively easy to plug in a RestTemplateCustomizer for any application that want this behavior, I think we shouldn't add these.

Aubade answered 27/1, 2020 at 10:25 Comment(0)
A
0

You can use OAuth2RestTemplate, which is tailored exactly for your purpose.

Ankara answered 27/1, 2020 at 15:55 Comment(0)
M
0

this works for me,

restTemplate.getInterceptors().add((outReq, bytes, clientHttpReqExec) -> {
            outReq.getHeaders().set(
                    HttpHeaders.AUTHORIZATION, "Bearer " + token
                  );
                  return clientHttpReqExec.execute(outReq, bytes);
                });
restTemplate.getForObject(...
restTemplate.postForObject(....
Marshamarshal answered 20/8, 2021 at 20:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.