[英]Is there any way to toggle Rest template to use Basic Auth or OAuth token?
My Service A makes a GET call to Service B, to get some details.我的服务 A 向服务 B 发出 GET 调用,以获取一些详细信息。 In my code, I've configured below that builds RestTemplate with Basic Auth creds.在我的代码中,我在下面配置了使用 Basic Auth 凭据构建 RestTemplate。
@Bean(name=Bobresttemplate)
public RestTemplate resttemplate(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder
.basicAuthentication("username", "password")
.build();
}
I use this in my RestClient.Java/ @Service classes by Autowiring.我通过自动装配在我的 RestClient.Java/@Service 类中使用它。
@Autowired
@Qualifier("Bobresttemplate")
RestTemplate restTemplate;
My Question: I'm building Bobresttemplate
with Basic Auth, now if I want to use this same Rest template but instead of Basic Auth, I want to use OAuth token to call 3rd party service.I want to acheive a functionality where based on a Toggle, I can use this same BobRestTemplate
but with either of Basic Auth or OAuth.我的问题:我正在使用 Basic Auth 构建Bobresttemplate
,现在如果我想使用相同的 Rest 模板而不是 Basic Auth,我想使用 OAuth 令牌来调用第 3 方服务。我想实现基于切换,我可以使用相同的BobRestTemplate
,但可以使用 Basic Auth 或 OAuth。
What extra config do I need to do?我需要做什么额外的配置? Do I need to create another Bean and build this RestTemplate with OAuth creds?我是否需要创建另一个 Bean 并使用 OAuth creds 构建此 RestTemplate?
I'm looking to understand whether do I need to create another Bean for configuring this template?我想了解是否需要创建另一个 Bean 来配置此模板? Or can I use Interceptors?或者我可以使用拦截器吗?
It may be helpfull to use spring.profiles
feature:使用spring.profiles
功能可能会有所帮助:
@Profile("basic-auth")
@Bean(name="Bobresttemplate")
public RestTemplate resttemplateBasic(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder
.basicAuthentication("username", "password")
.build();
}
@Profile("jwt")
@Bean(name="Bobresttemplate")
public RestTemplate resttemplateJwt(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder
...
.build();
}
so in config you just enable profile that you need (no changes in place of injecting resttemplate bean):所以在配置中你只需启用你需要的配置文件(没有改变来代替注入 resttemplate bean):
spring.profiles.active=jwt
or或者
spring.profiles.active=basic-auth
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.