带有承载授权的RestTemplate [英] RestTemplate with Bearer Authorization
问题描述
是否可以使用RestTemplateBuilder创建仅带有载体标头和令牌的RestTemplate实例?
Is it possible to create with RestTemplateBuilder an instance of RestTemplate with just the bearer header and token?
我知道我可以使用RestTemplate交换并在HttpEntity中设置我的标头,但是否可以执行以下操作:
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;
请记住,您仍然可以照常使用 restTemplate
对象,设置标头等,但 Bearer
标头将始终被覆盖带有"token"
的代码会导致拦截器在发出请求之前立即应用
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
这篇关于带有承载授权的RestTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!