I need to call a Rest API from my Apache Camel route. The Rest API is secured with a token that can be obtained on andother API.
My demo route looks like following:
from("direct:iot")
.id("iot")
.setHeader(Exchange.HTTP_METHOD, constant("POST"))
.setHeader(Exchange.CONTENT_TYPE, constant("application/x-www-form-urlencoded"))
.setBody(simple(STR."username=\{USERNAME}&password=\{PASSWORD}&grant_type=password&client_id=iot-api-client&client_secret=\{CLIENT_SECRET}"))
.to(TOKEN_URL)
.unmarshal().json(JsonLibrary.Gson)
.process(e -> {
Map body = e.getIn().getBody(Map.class);
e.getIn().setHeader("Authorization",
STR."Bearer \{body.get("access_token")}");
})
.removeHeader("*")
.setHeader(Exchange.HTTP_METHOD, constant("GET"))
.to(STR."\{BASE_URL}\{RESOURCE_URI}")
.log("${body}");
It works but it seems quite complicatied to me (I should also add some error handling, token caching etc.). I wonder if it can be simplified somehow.
In the APACHE CAMEL 4.2 WHAT'S NEW they write:
"The camel-http component now supports OAuth 2.0 client authentication."
Unfortunately I was not able to find any details.
You can see this unit test
HttpOAuth2AuthenticationTest
and there is also a little bit docs as there are new oauth options on the http component.