REST service call with Camel which requires authen

2019-04-06 08:54发布

问题:

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.

Does Spring Restemplate or apache camel has some api to support the same?

回答1:

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;
        }
}

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}");
    }
}

So, here the token is getting consumed from the tokenObj bean (instance of RestTokenProducerRoute which has method getRefreshedToken() defined. It returns the stored token.

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.