io.vertx.ext.auth.oauth2.providers.KeycloakAuth Java Examples

The following examples show how to use io.vertx.ext.auth.oauth2.providers.KeycloakAuth. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OAuth2KeycloakIT.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp(TestContext should) {
  final Async test = should.async();

  OAuth2Options options = new OAuth2Options()
    .setFlow(OAuth2FlowType.PASSWORD)
    .setClientID("public-client")
    .setTenant("vertx-test")
    .setSite(site + "/auth/realms/{tenant}");

  options.getHttpClientOptions().setTrustAll(true);

  KeycloakAuth.discover(
    rule.vertx(),
    options,
    discover -> {
      should.assertTrue(discover.succeeded());
      keycloak = discover.result();
      test.complete();
    });
}
 
Example #2
Source File: Oauth2TokenTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void testNullScope() throws Exception {
  super.setUp();
  oauth2 = KeycloakAuth.create(vertx, OAuth2FlowType.AUTH_CODE, keycloakConfig);

  JsonObject json = new JsonObject(
    "{\n" +
      "    \"access_token\":\"xyz\",\n" +
      "    \"expires_in\":60,\n" +
      "    \"token_type\":\"bearer\",\n" +
      "    \"not-before-policy\":0,\n" +
      "    \"scope\":null\n" +
      "}"
  );

  try {
    AccessToken token = new AccessTokenImpl(json, oauth2);
  } catch (RuntimeException e) {
    fail();
  }
}
 
Example #3
Source File: OAuth2KeycloakIT.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldIntrospectAccessToken(TestContext should) {
  final Async test = should.async();

  keycloak.authenticate(new JsonObject().put("username", "test-user").put("password", "tiger"), authn -> {
    should.assertTrue(authn.succeeded());
    should.assertNotNull(authn.result());

    // generate a access token from the user
    User token = authn.result();

    OAuth2Options options = new OAuth2Options()
      .setFlow(OAuth2FlowType.PASSWORD)
      .setClientID("confidential-client")
      .setTenant("vertx-test")
      .setSite(site + "/auth/realms/{realm}")
      .setClientSecret("62b8de48-672e-4287-bb1e-6af39aec045e");

    options.getHttpClientOptions().setTrustAll(true);

    // get a auth handler for the confidential client
    KeycloakAuth.discover(
      rule.vertx(),
      options,
      discover -> {
        should.assertTrue(discover.succeeded());
        OAuth2Auth confidential = discover.result();

        confidential.authenticate(token.principal(), introspect -> {
          should.assertTrue(introspect.succeeded());
          test.complete();
        });
      });
  });
}
 
Example #4
Source File: Oauth2TokenTest.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Test
public void keycloakTest() throws Exception {
  super.setUp();
  oauth2 = KeycloakAuth.create(vertx, OAuth2FlowType.AUTH_CODE, keycloakConfig);

  AccessToken token = new AccessTokenImpl(keycloakToken, oauth2);

  assertNotNull(token.opaqueAccessToken());
  assertNotNull(token.opaqueRefreshToken());
  assertNull(token.accessToken());
}
 
Example #5
Source File: KeycloakOAuthFactory.java    From apiman with Apache License 2.0 5 votes vote down vote up
private static OAuth2AuthHandler standardAuth(Vertx vertx, Router router, VertxEngineConfig apimanConfig, JsonObject authConfig, OAuth2FlowType flowType)  {
    String proto = apimanConfig.isSSL() ? "https://" : "http://";
    int port = apimanConfig.getPort(ApiVerticle.VERTICLE_TYPE);
    String hostname = Optional.of(apimanConfig.getPublicEndpoint()).orElse(apimanConfig.getHostname());
    String redirect = proto + hostname + ":" + port; // Redirect back here to *after* auth.
    // Set up KC OAuth2 Authentication
    OAuth2AuthHandler auth = OAuth2AuthHandler.create(KeycloakAuth.create(vertx, flowType, authConfig), redirect);
    // Callback can be anything (as long as it's not already used by something else).
    auth.setupCallback(router.get("/callback"));
    return auth;
}
 
Example #6
Source File: KeycloakOAuth2.java    From apiman with Apache License 2.0 5 votes vote down vote up
@Override
public Authenticator authenticate(Vertx vertx, Map<String, String> config, MultiMap headerMap, Handler<AsyncResult<Void>> resultHandler) {

    OAuth2FlowType flowType = getFlowType(config.get("flowType"));
    JsonObject params = new JsonObject();
    if (config.get("username") != null) {
        params.put("username", config.get("username"));
    }
    if (config.get("password") != null) {
        params.put("password", config.get("password"));
    }

    OAuth2Auth oauth2 = KeycloakAuth.create(vertx,  flowType, mapToJson(config));

    oauth2.getToken(params, tokenResult -> {
        if (tokenResult.succeeded()) {
            log.debug("OAuth2 Keycloak exchange succeeded.");
            AccessToken token = tokenResult.result();
            headerMap.set("Authorization", "Bearer " + token.principal().getString("access_token"));
            resultHandler.handle(Future.succeededFuture());
        } else {
            log.error("Access Token Error: {0}.", tokenResult.cause().getMessage());
            resultHandler.handle(Future.failedFuture(tokenResult.cause()));
        }
      });
    return this;
}
 
Example #7
Source File: APIGatewayVerticle.java    From vertx-blueprint-microservice with Apache License 2.0 4 votes vote down vote up
@Override
public void start(Future<Void> future) throws Exception {
  super.start();

  // get HTTP host and port from configuration, or use default value
  String host = config().getString("api.gateway.http.address", "localhost");
  int port = config().getInteger("api.gateway.http.port", DEFAULT_PORT);

  Router router = Router.router(vertx);
  // cookie and session handler
  enableLocalSession(router);

  // body handler
  router.route().handler(BodyHandler.create());

  // version handler
  router.get("/api/v").handler(this::apiVersion);

  // create OAuth 2 instance for Keycloak
  oauth2 = KeycloakAuth.create(vertx, OAuth2FlowType.AUTH_CODE, config());

  router.route().handler(UserSessionHandler.create(oauth2));

  String hostURI = buildHostURI();

  // set auth callback handler
  router.route("/callback").handler(context -> authCallback(oauth2, hostURI, context));

  router.get("/uaa").handler(this::authUaaHandler);
  router.get("/login").handler(this::loginEntryHandler);
  router.post("/logout").handler(this::logoutHandler);

  // api dispatcher
  router.route("/api/*").handler(this::dispatchRequests);

  // static content
  router.route("/*").handler(StaticHandler.create());

  // enable HTTPS
  HttpServerOptions httpServerOptions = new HttpServerOptions()
    .setSsl(true)
    .setKeyStoreOptions(new JksOptions().setPath("server.jks").setPassword("123456"));

  // create http server
  vertx.createHttpServer(httpServerOptions)
    .requestHandler(router::accept)
    .listen(port, host, ar -> {
      if (ar.succeeded()) {
        publishApiGateway(host, port);
        future.complete();
        logger.info("API Gateway is running on port " + port);
        // publish log
        publishGatewayLog("api_gateway_init_success:" + port);
      } else {
        future.fail(ar.cause());
      }
    });
}