Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
camel snippet using oauth to get an auth token and use it to request a secured rest service
from("timer://scheduler?period=30s")
.log("get access token")
.to("direct:authService");
from("direct:authService").tracing()
.setHeader(Exchange.HTTP_PATH)
.simple("<auth service context>/oauth2/token")
.setHeader("CamelHttpMethod")
.simple("POST")
.setHeader("Content-Type")
.simple("application/x-www-form-urlencoded")
.setHeader("Accept")
.simple("application/json")
.setBody()
.constant("grant_type=client_credentials&client_id=<client id>&client_secret=<client sec>")
.to("https4://<remote auth service url>")
.convertBodyTo(String.class)
.log("response from API: " + body())
.choice()
.when().simple("${header.CamelHttpResponseCode} == 200")
.unmarshal().json(JsonLibrary.Jackson, AccessResponseToken.class)
.setHeader("jwt").simple("${body.access_token}")
.to("direct:<some direct route>")
.otherwise()
.log("Not Authenticated!!!");
from("direct:<some direct route>").tracing()
.log("body: " + body().toString())
.setBody().constant(null)
.setHeader(Exchange.HTTP_PATH)
.simple("v1/canais")
.setHeader("CamelHttpMethod")
.simple("GET")
.setHeader("Accept")
.simple("application/json")
.setHeader("Authorization")
.simple("${header.jwt}") // <<<<<< HERE YOU GET YOUR AUTH TOKEN GRANTED IN PREVIOUS ROUTE >>>>>>
.to("https4://<remote secured service url>")
.convertBodyTo(String.class)
.choice()
.when().simple("${header.CamelHttpResponseCode} == 200")
.setBody().javaScript(""
+ " canais = JSON.parse(request.body);"
+ " idx = Math.floor(Math.random() * (canais.length - 1));"
+ " result = canais[idx].id;"
+ "")
.log("response from globosat API: " + body())
.to("direct:<another route>")
.otherwise()
.log("Error!!!");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.