简体   繁体   中英

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.

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 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 override with "token" cause the interceptors apply right before the request is made

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

Thanks :)

    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.

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.

您可以使用OAuth2RestTemplate ,它完全适合您的目的。

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(....

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