Skip to content

Instantly share code, notes, and snippets.

@dermatologist
Forked from rafaeltuelho/camel-raw-oauth.java
Created November 5, 2018 20:51
Show Gist options
  • Save dermatologist/52ceb19850c9a3b59d3bff123b602020 to your computer and use it in GitHub Desktop.
Save dermatologist/52ceb19850c9a3b59d3bff123b602020 to your computer and use it in GitHub Desktop.
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