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

查看:614
本文介绍了使用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;
        }
}

第二条路线可以调用后续的apis第一条路线生成的令牌,就像这样。必须添加错误处理方案,其中令牌可能无效或已过期。但我想这将是另一个需要解决的问题。

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天全站免登陆