Skip to content

Instantly share code, notes, and snippets.

@pmlopes
Created March 20, 2017 19:27
Show Gist options
  • Save pmlopes/94a55db24cb9c6b4dff2649d539b7f92 to your computer and use it in GitHub Desktop.
Save pmlopes/94a55db24cb9c6b4dff2649d539b7f92 to your computer and use it in GitHub Desktop.
How to consume a Oauth2 project API with Vert.x
// setup an Oauth2 provider for Keycloak
OAuth2Auth oauth2 = KeycloakAuth.create(vertx, OAuth2FlowType.PASSWORD, config());
// credentials
JsonObject credentials = new JsonObject()
.put("username", username)
.put("password", password);
// create an WebClient to make request
final WebClient client = WebClient.create(vertx);
// get a OAuth2 token using the Client Credential Flow
oauth2.getToken(credentials, getToken -> {
if (getToken.failed()) {
getToken.cause().printStackTrace(System.err);
return;
}
AccessToken token = getToken.result();
// Make the real request to the protected resource
client
.get(apiEndPoint)
.putHeader("Authorization", "Bearer " + token.principal().getString("access_token"))
.send(req -> {
if (req.failed()) {
req.cause().printStackTrace(System.err);
return;
}
System.out.println(req.result().body().toString());
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment