REST service call with Camel which requires authentication api called first(使用 Camel 的 REST 服务调用需要首先调用身份验证 api)
问题描述
Camel 必须调用 REST 服务进行某些集成,但是,REST 服务有一个身份验证 api (POST api),需要首先调用它来获取令牌,然后必须调用嵌入令牌的其他后续 api 调用在 HTTP 请求的标头中.
Camel has to call REST service for some integration, However, the REST service has one authentication api (POST api) which needs to be called first to get a token and then other subsequent api calls has to be invoked with the token embedded in header of HTTP requests.
Spring Restemplate 或 apache camel 是否有一些 api 来支持相同的功能?
Does Spring Restemplate or apache camel has some api to support the same?
推荐答案
遵循@gusto2 方法,它几乎工作正常.
Followed @gusto2 approach, Its pretty much working fine.
所以,我创建了两条路由 --> 第一个是基于定时器的,如下所示,它生成令牌,定期刷新它(因为路由是基于定时器的)并将令牌存储在局部变量中以供某些人重用其他路线.
SO, I created two routes --> First one is a timer based like below, this generates the token, periodically refreshes it(since the route is timer based) and stores the token in a local variable for being reused by some other route.
@Component
public class RestTokenProducerRoute extends RouteBuilder {
private String refreshedToken;
@Override
public void configure() throws Exception {
restConfiguration().producerComponent("http4");
from("timer://test?period=1200000") //called every 20 mins
.process(
exchange -> exchange.getIn().setBody(
new UserKeyRequest("apiuser", "password")))
.marshal(userKeyRequestJacksonFormat) //convert it to JSON
.setHeader(Exchange.HTTP_METHOD, constant("POST"))
.setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
.to("http4://localhost:8085/Service/Token")
.unmarshal(userKeyResponseJacksonFormat)
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
UserKeyResponse response= exchange.getIn().getBody(
UserKeyResponse.class); //get the response object
System.out.println(response + "========>>>>>>" +
response.getResult());
setRefreshedToken(response.getResult()); //store the token in some object
}
}).log("${body}");
}
public String getRefreshedToken() {
return refreshedToken;
}
public void setRefreshedToken(String refreshedToken) {
this.refreshedToken = refreshedToken;
}
}
第二个路由可以调用后续的api,这些api将使用第一个路由生成的令牌,它会是这样的.必须添加错误处理场景,其中令牌可能无效或过期.但我想这将是另一个需要解决的问题.
And the second route can call subsequent apis which will use the token generated by the first route, it would be something like this. Have to add error handling scenarios, where token might not be valid or expired. But I guess that would be separate concern to solve.
@Component
public class RestTokenUserOnboardRoute extends RouteBuilder {
private JacksonDataFormat OtherDomainUserRequestJacksonFormat = new JacksonDataFormat(
OtherDomainUserRequest.class);
private JacksonDataFormat OtherDomainUserResponseJacksonFormat = new JacksonDataFormat(
OtherDomainUserResponse.class);
@Override
public void configure() throws Exception {
restConfiguration().producerComponent("http4");
//This route is subscribed to a Salesforce topic, which gets invoked when there is any new messages in the topic.
from("salesforce:CamelTestTopic?sObjectName=MyUser__c&sObjectClass="+MyUser__c.class.getName()))
.convertBodyTo(OtherDomainUserRequest.class)
.marshal(OtherDomainUserRequestJacksonFormat).log("${body}")
.setHeader(Exchange.HTTP_METHOD, constant("POST"))
.setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
.log("The token being passed is ==> ${bean:tokenObj?method=getRefreshedToken}")
.setHeader("Authorization", simple("${bean:tokenObj?method=getRefreshedToken}"))
.to("http4://localhost:8085/Service/DomainUser")
.unmarshal(OtherDomainUserResponseJacksonFormat)
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
OtherDomainUserResponse response = exchange.getIn().getBody(
OtherDomainUserResponse.class);
System.out.println(response + "==================>>>>>> " + response.getStatusCode());
}
}).log("${body}");
}
}
所以,这里的令牌是从 tokenObj
bean 中消耗的(RestTokenProducerRoute
的实例,它定义了方法 getRefreshedToken()
.它返回存储的令牌.
So, here the token is getting consumed from the tokenObj
bean (instance of RestTokenProducerRoute
which has method getRefreshedToken()
defined. It returns the stored token.
不用说,您已经在 camelcontext 注册表中设置了 bean 以及其他设置(如组件、路由等),如下所示.在我的情况下,如下所示.
Needless to say, you have set the bean in camelcontext registry as follows along with other settings (like component, route etc). In my case it was as follows.
@Autowired
public RestTokenUserOnboardRoute userOnboardRoute;
@Autowired
public RestTokenProducerRoute serviceTokenProducerRoute;
@Autowired
private RestTokenProducerRoute tokenObj;
@Override
protected CamelContext createCamelContext() throws Exception {
SimpleRegistry registry = new SimpleRegistry();
registry.put("tokenObj", tokenObj); //the tokenObj bean,which can be used anywhere in the camelcontext
SpringCamelContext camelContext = new SpringCamelContext();
camelContext.setRegistry(registry); //add the registry
camelContext.setApplicationContext(getApplicationContext());
camelContext.addComponent("salesforce", salesforceComponent());
camelContext.getTypeConverterRegistry().addTypeConverter(DomainUserRequest.class, MyUser__c.class, new MyTypeConverter());
camelContext.addRoutes(route()); //Some other route
camelContext.addRoutes(serviceTokenProducerRoute); //Token producer Route
camelContext.addRoutes(userOnboardRoute); //Subsequent API call route
camelContext.start();
return camelContext;
}
这解决了我动态设置令牌的问题,因为执行其他路由会产生令牌.
This solves my problem of setting token dynamically where token is getting produced as a result of execution of some other route.
这篇关于使用 Camel 的 REST 服务调用需要首先调用身份验证 api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Camel 的 REST 服务调用需要首先调用身份验证 api
基础教程推荐
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 降序排序:Java Map 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01