使用 Camel 调用 REST 服务,需要先调用身份验证 api [英] REST service call with Camel which requires authentication api called first

查看:33
本文介绍了使用 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,我创建了两条路由 --> 第一个是基于下面的计时器,它生成令牌,定期刷新它(因为路由是基于计时器的)并将令牌存储在局部变量中以供某些人重用其他路线.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆