io.vertx.ext.auth.oauth2.OAuth2FlowType Java Examples

The following examples show how to use io.vertx.ext.auth.oauth2.OAuth2FlowType. 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: 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 #2
Source File: OAuth2API.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
/**
 * The client sends the end-user's browser to this endpoint to request their authentication and consent. This endpoint is used in the code and implicit OAuth 2.0 flows which require end-user interaction.
 *
 * see: https://tools.ietf.org/html/rfc6749
 */
public String authorizeURL(JsonObject params) {
  final JsonObject query = params.copy();

  if (config.getFlow() != OAuth2FlowType.AUTH_CODE) {
    throw new IllegalStateException("authorization URL cannot be computed for non AUTH_CODE flow");
  }

  if (query.containsKey("scopes")) {
    // scopes have been passed as a list so the provider must generate the correct string for it
    query.put("scope", String.join(config.getScopeSeparator(), query.getJsonArray("scopes").getList()));
    query.remove("scopes");
  }

  query.put("response_type", "code");
  query.put("client_id", config.getClientID());

  final String path = config.getAuthorizationPath();
  final String url = path.charAt(0) == '/' ? config.getSite() + path : path;

  return url + '?' + stringify(query);
}
 
Example #3
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 #4
Source File: AzureADAuth.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
/**
 * Create a OAuth2Auth provider for Microsoft Azure Active Directory
 *
 * @param clientId          the client id given to you by Azure
 * @param clientSecret      the client secret given to you by Azure
 * @param guid              the guid of your application given to you by Azure
 * @param httpClientOptions custom http client options
 */
static OAuth2Auth create(Vertx vertx, String clientId, String clientSecret, String guid, HttpClientOptions httpClientOptions) {
  return
    OAuth2Auth.create(vertx, new OAuth2Options()
      .setHttpClientOptions(httpClientOptions)
      .setFlow(OAuth2FlowType.AUTH_CODE)
      .setClientID(clientId)
      .setClientSecret(clientSecret)
      .setTenant(guid)
      .setSite("https://login.windows.net/{tenant}")
      .setTokenPath("/oauth2/token")
      .setAuthorizationPath("/oauth2/authorize")
      .setScopeSeparator(",")
      .setExtraParameters(
        new JsonObject().put("resource", "{tenant}")));
}
 
Example #5
Source File: GoogleAuth.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
/**
 * Create a OAuth2Auth provider for Google
 *
 * @param clientId          the client id given to you by Google
 * @param clientSecret      the client secret given to you by Google
 * @param httpClientOptions custom http client options
 */
static OAuth2Auth create(Vertx vertx, String clientId, String clientSecret, HttpClientOptions httpClientOptions) {
  return
    OAuth2Auth.create(vertx, new OAuth2Options()
      .setHttpClientOptions(httpClientOptions)
      .setFlow(OAuth2FlowType.AUTH_CODE)
      .setClientID(clientId)
      .setClientSecret(clientSecret)
      .setSite("https://accounts.google.com")
      .setTokenPath("https://www.googleapis.com/oauth2/v3/token")
      .setAuthorizationPath("/o/oauth2/auth")
      .setIntrospectionPath("https://www.googleapis.com/oauth2/v3/tokeninfo")
      .setUserInfoPath("https://www.googleapis.com/oauth2/v3/userinfo")
      .setJwkPath("https://www.googleapis.com/oauth2/v3/certs")
      .setUserInfoParameters(new JsonObject()
        .put("alt", "json"))
      .setScopeSeparator(" "));
}
 
Example #6
Source File: GoogleAuth.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
/**
 * Create a OAuth2Auth provider for Google Service Account (Server to Server)
 *
 * @param serviceAccountJson the configuration json file from your Google API page
 * @param httpClientOptions  custom http client options
 */
static OAuth2Auth create(Vertx vertx, JsonObject serviceAccountJson, HttpClientOptions httpClientOptions) {
  return
    OAuth2Auth.create(vertx, new OAuth2Options()
      .setHttpClientOptions(httpClientOptions)
      .setFlow(OAuth2FlowType.AUTH_JWT)
      .setClientID(serviceAccountJson.getString("client_id"))
      .setSite("https://accounts.google.com")
      .setTokenPath(serviceAccountJson.getString("token_uri"))
      .addPubSecKey(new PubSecKeyOptions()
        .setAlgorithm("RS256")
        .setBuffer(serviceAccountJson.getString("private_key")))
      .setJWTOptions(new JWTOptions()
        .setAlgorithm("RS256")
        .setExpiresInMinutes(60)
        .addAudience(serviceAccountJson.getString("token_uri"))
        .setIssuer(serviceAccountJson.getString("client_email"))));
}
 
Example #7
Source File: OAuth2FailureTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void unknownHost() {
  OAuth2Auth auth = OAuth2Auth.create(vertx, new OAuth2Options()
    .setFlow(OAuth2FlowType.AUTH_CODE)
    .setClientID("client-id")
    .setClientSecret("client-secret")
    .setSite("http://zlouklfoux.net.com.info.pimpo.molo"));
  auth.authenticate(tokenConfig, res -> {
    if (res.failed()) {
      assertThat(res.cause(), instanceOf(UnknownHostException.class));
      testComplete();
    } else {
      fail("Should have failed");
    }
  });
  await();
}
 
Example #8
Source File: OAuth2AuthHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testBearerOnly() throws Exception {

  // lets mock a oauth2 server using code auth code flow
  OAuth2Auth oauth2 = OAuth2Auth.create(vertx, new OAuth2Options().setFlow(OAuth2FlowType.AUTH_CODE).setClientID("client-id"));
  OAuth2AuthHandler oauth2Handler = OAuth2AuthHandler.create(vertx, oauth2);

  // protect everything under /protected
  router.route("/protected/*").handler(oauth2Handler);
  // mount some handler under the protected zone
  router.route("/protected/somepage").handler(rc -> {
    assertNotNull(rc.user());
    rc.response().end("Welcome to the protected resource!");
  });


  testRequest(HttpMethod.GET, "/protected/somepage", 401, "Unauthorized");
  // Now try again with fake credentials
  testRequest(HttpMethod.GET, "/protected/somepage", req -> req.putHeader("Authorization", "Bearer 4adc339e0"), 401, "Unauthorized", "Unauthorized");
}
 
Example #9
Source File: AmazonCognitoAuth.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
/**
 * Create a OAuth2Auth provider for Amazon Cognito
 *
 * @param region            the region to use
 * @param clientId          the client id given to you by Amazon Cognito
 * @param clientSecret      the client secret given to you by Amazon Cognito
 * @param userPoolId        the userPoolId of your application given to you by Amazon Cognito
 * @param httpClientOptions custom http client options
 */
static OAuth2Auth create(Vertx vertx, String region, String clientId, String clientSecret, String userPoolId, HttpClientOptions httpClientOptions) {
  if (region == null) {
    throw new IllegalStateException("region cannot be null");
  }

  return
    OAuth2Auth.create(vertx, new OAuth2Options()
      .setHttpClientOptions(httpClientOptions)
      .setFlow(OAuth2FlowType.AUTH_CODE)
      .setClientID(clientId)
      .setClientSecret(clientSecret)
      .setTenant(userPoolId)
      .setSite("https://cognito-idp." + region + ".amazonaws.com/{tenant}")
      .setTokenPath("/oauth2/token")
      .setAuthorizationPath("/oauth2/authorize")
      .setUserInfoPath("/oauth2/userInfo")
      .setJwkPath("/.well-known/jwks.json")
      .setLogoutPath("/logout")
      .setScopeSeparator("+"));
}
 
Example #10
Source File: GithubAuth.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
/**
 * Create a OAuth2Auth provider for Github
 *
 * @param clientId the client id given to you by Github
 * @param clientSecret the client secret given to you by Github
 * @param httpClientOptions custom http client options
 */
static OAuth2Auth create(Vertx vertx, String clientId, String clientSecret, HttpClientOptions httpClientOptions) {
  return
    OAuth2Auth.create(vertx, new OAuth2Options()
      .setHttpClientOptions(httpClientOptions)
      .setFlow(OAuth2FlowType.AUTH_CODE)
      .setClientID(clientId)
      .setClientSecret(clientSecret)
      .setSite("https://github.com/login")
      .setTokenPath("/oauth/access_token")
      .setAuthorizationPath("/oauth/authorize")
      .setUserInfoPath("https://api.github.com/user")
      .setScopeSeparator(" ")
      .setHeaders(new JsonObject()
        .put("User-Agent", "vertx-auth-oauth2")));
}
 
Example #11
Source File: IBMCloudAuth.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
/**
 * Create a OAuth2Auth provider for IBM Cloud
 *
 * @param region            the region to use
 * @param clientId          the client id given to you by IBM Cloud
 * @param clientSecret      the client secret given to you by IBM Cloud
 * @param guid              the guid of your application given to you by IBM Cloud
 * @param httpClientOptions custom http client options
 */
static OAuth2Auth create(Vertx vertx, String region, String clientId, String clientSecret, String guid, HttpClientOptions httpClientOptions) {
  if (region == null) {
    throw new IllegalStateException("region cannot be null");
  }

  return
    OAuth2Auth.create(vertx, new OAuth2Options()
      .setHttpClientOptions(httpClientOptions)
      .setFlow(OAuth2FlowType.AUTH_CODE)
      .setClientID(clientId)
      .setClientSecret(clientSecret)
      .setTenant(guid)
      .setSite("https://" + region + ".appid.cloud.ibm.com/oauth/v4/{tenant}")
      .setTokenPath("/token")
      .setAuthorizationPath("/authorization")
      .setJwkPath("/publickeys")
      .setUserInfoPath("/userinfo"));
}
 
Example #12
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 #13
Source File: SalesforceAuth.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Create a OAuth2Auth provider for Salesforce
 *
 * @param clientId          the client id given to you by Salesforce
 * @param clientSecret      the client secret given to you by Salesforce
 * @param httpClientOptions custom http client options
 */
static OAuth2Auth create(Vertx vertx, String clientId, String clientSecret, HttpClientOptions httpClientOptions) {
  return
    OAuth2Auth.create(vertx, new OAuth2Options()
      .setHttpClientOptions(httpClientOptions)
      .setFlow(OAuth2FlowType.AUTH_CODE)
      .setClientID(clientId)
      .setClientSecret(clientSecret)
      .setSite("https://login.salesforce.com")
      .setTokenPath("/services/oauth2/token")
      .setAuthorizationPath("/services/oauth2/authorize")
      .setScopeSeparator("+"));
}
 
Example #14
Source File: FoursquareAuth.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Create a OAuth2Auth provider for Foursquare
 *
 * @param clientId          the client id given to you by Foursquare
 * @param clientSecret      the client secret given to you by Foursquare
 * @param httpClientOptions custom http client options
 */
static OAuth2Auth create(Vertx vertx, String clientId, String clientSecret, HttpClientOptions httpClientOptions) {
  return
    OAuth2Auth.create(vertx, new OAuth2Options()
      .setHttpClientOptions(httpClientOptions)
      .setClientID(clientId)
      .setClientSecret(clientSecret)
      .setFlow(OAuth2FlowType.AUTH_CODE)
      .setSite("https://foursquare.com")
      .setTokenPath("/oauth2/access_token")
      .setAuthorizationPath("/oauth2/authenticate")
      .setUserInfoPath("/users/self"));
}
 
Example #15
Source File: TwitterAuth.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Create a OAuth2Auth provider for Twitter
 *
 * @param clientId          the client id given to you by Twitter
 * @param clientSecret      the client secret given to you by Twitter
 * @param httpClientOptions custom http client options
 */
static OAuth2Auth create(Vertx vertx, String clientId, String clientSecret, HttpClientOptions httpClientOptions) {
  return
    OAuth2Auth.create(vertx, new OAuth2Options()
      .setHttpClientOptions(httpClientOptions)
      .setFlow(OAuth2FlowType.AUTH_CODE)
      .setClientID(clientId)
      .setClientSecret(clientSecret)
      .setSite("https://api.twitter.com")
      .setTokenPath("/oauth/access_token")
      .setAuthorizationPath("/oauth/authorize")
      .setUserInfoPath("/1.1/users/show.json"));
}
 
Example #16
Source File: BoxAuth.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Create a OAuth2Auth provider for App.net
 *
 * @param clientId          the client id given to you by box.com
 * @param clientSecret      the client secret given to you by box.com
 * @param httpClientOptions custom http client options
 */
static OAuth2Auth create(Vertx vertx, String clientId, String clientSecret, HttpClientOptions httpClientOptions) {
  return
    OAuth2Auth.create(vertx, new OAuth2Options()
      .setHttpClientOptions(httpClientOptions)
      .setFlow(OAuth2FlowType.AUTH_CODE)
      .setClientID(clientId)
      .setClientSecret(clientSecret)
      .setSite("https://account.box.com")
      .setTokenPath("/api/oauth2/token")
      .setAuthorizationPath("/api/oauth2/authorize")
      .setUserInfoPath("/users/me")
      .setScopeSeparator(" "));
}
 
Example #17
Source File: ShopifyAuth.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Create a OAuth2Auth provider for Shopify
 *
 * @param clientId          the client id given to you by Shopify
 * @param clientSecret      the client secret given to you by Shopify
 * @param shop              your shop name
 * @param httpClientOptions custom http client options
 */
static OAuth2Auth create(Vertx vertx, String clientId, String clientSecret, String shop, HttpClientOptions httpClientOptions) {
  return
    OAuth2Auth.create(vertx, new OAuth2Options()
      .setHttpClientOptions(httpClientOptions)
      .setFlow(OAuth2FlowType.AUTH_CODE)
      .setClientID(clientId)
      .setClientSecret(clientSecret)
      .setTenant(shop)
      .setSite("https://{tenant}.myshopify.com")
      .setTokenPath("/admin/oauth/access_token")
      .setAuthorizationPath("/admin/oauth/authorize")
      .setUserInfoPath("/admin/shop.json")
      .setScopeSeparator(","));
}
 
Example #18
Source File: OAuth2AuthCodeErrorTest.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
  super.setUp();
  oauth2 = OAuth2Auth.create(vertx, new OAuth2Options()
    .setFlow(OAuth2FlowType.AUTH_CODE)
    .setClientID("client-id")
    .setClientSecret("client-secret")
    .setSite("http://localhost:8080"));

  final CountDownLatch latch = new CountDownLatch(1);

  server = vertx.createHttpServer().requestHandler(req -> {
    if (req.method() == HttpMethod.POST && "/oauth/token".equals(req.path())) {
      assertEquals("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=", req.getHeader("Authorization"));
      req.setExpectMultipart(true).bodyHandler(buffer -> {
        try {
          assertEquals(config, queryToJSON(buffer.toString()));
        } catch (UnsupportedEncodingException e) {
          fail(e);
        }
        req.response().putHeader("Content-Type", "application/json").end(fixture.encode());
      });
    } else {
      req.response().setStatusCode(400).end();
    }
  }).listen(8080, ready -> {
    if (ready.failed()) {
      throw new RuntimeException(ready.cause());
    }
    // ready
    latch.countDown();
  });

  latch.await();
}
 
Example #19
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 #20
Source File: OAuth2PasswordTest.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
  super.setUp();
  oauth2 = OAuth2Auth.create(vertx, new OAuth2Options()
    .setFlow(OAuth2FlowType.PASSWORD)
    .setClientID("client-id")
    .setClientSecret("client-secret")
    .setSite("http://localhost:8080"));

  final CountDownLatch latch = new CountDownLatch(1);

  server = vertx.createHttpServer().requestHandler(req -> {
    if (req.method() == HttpMethod.POST && "/oauth/token".equals(req.path())) {
      assertEquals("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=", req.getHeader("Authorization"));
      req.setExpectMultipart(true).bodyHandler(buffer -> {
        try {
          assertEquals(config, queryToJSON(buffer.toString()));
        } catch (UnsupportedEncodingException e) {
          fail(e);
        }
        req.response().putHeader("Content-Type", "application/json").end(fixture.encode());
      });
    } else {
      req.response().setStatusCode(400).end();
    }
  }).listen(8080, ready -> {
    if (ready.failed()) {
      throw new RuntimeException(ready.cause());
    }
    // ready
    latch.countDown();
  });

  latch.await();
}
 
Example #21
Source File: OAuth2FailureTest.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
  dns = new FakeDNSServer().store(question -> Collections.emptySet());
  dns.start();
  super.setUp();
  oauth2 = OAuth2Auth.create(vertx, new OAuth2Options()
    .setFlow(OAuth2FlowType.AUTH_CODE)
    .setClientID("client-id")
    .setClientSecret("client-secret")
    .setSite("http://localhost:8080"));

  final CountDownLatch latch = new CountDownLatch(1);

  server = vertx.createHttpServer().requestHandler(req -> {
    if (req.method() == HttpMethod.POST && "/oauth/token".equals(req.path())) {
      assertEquals("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=", req.getHeader("Authorization"));
      req.setExpectMultipart(true).bodyHandler(buffer -> {
        try {
          assertEquals(config, queryToJSON(buffer.toString()));
        } catch (UnsupportedEncodingException e) {
          fail(e);
        }
        req.response().setStatusCode(code).end();
      });
    } else {
      req.response().setStatusCode(400).end();
    }
  }).listen(8080, ready -> {
    if (ready.failed()) {
      throw new RuntimeException(ready.cause());
    }
    // ready
    latch.countDown();
  });

  latch.await();
}
 
Example #22
Source File: OAuth2ClientTest.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
  super.setUp();
  oauth2 = OAuth2Auth.create(vertx, new OAuth2Options()
    .setFlow(OAuth2FlowType.CLIENT)
    .setClientID("client-id")
    .setClientSecret("client-secret")
    .setSite("http://localhost:8080"));

  final CountDownLatch latch = new CountDownLatch(1);

  server = vertx.createHttpServer().requestHandler(req -> {
    if (req.method() == HttpMethod.POST && "/oauth/token".equals(req.path())) {
      assertEquals("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=", req.getHeader("Authorization"));
      req.setExpectMultipart(true).bodyHandler(buffer -> {
        try {
          assertEquals(config, queryToJSON(buffer.toString()));
        } catch (UnsupportedEncodingException e) {
          fail(e);
        }
        req.response().putHeader("Content-Type", "application/json").end(fixture.encode());
      });
    } else {
      req.response().setStatusCode(400).end();
    }
  }).listen(8080, ready -> {
    if (ready.failed()) {
      throw new RuntimeException(ready.cause());
    }
    // ready
    latch.countDown();
  });

  latch.await();
}
 
Example #23
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 #24
Source File: OAuth2ErrorsTest.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
  super.setUp();
  oauth2 = OAuth2Auth.create(vertx, new OAuth2Options()
    .setFlow(OAuth2FlowType.AUTH_CODE)
      .setClientID("client-id")
      .setClientSecret("client-secret")
      .setSite("http://localhost:8080"));

  final CountDownLatch latch = new CountDownLatch(1);

  server = vertx.createHttpServer().requestHandler(req -> {
    if (req.method() == HttpMethod.POST && "/oauth/token".equals(req.path())) {
      req.setExpectMultipart(true).bodyHandler(buffer ->
        req.response().putHeader("Content-Type", "application/json").end(fixture.encode()));
    } else {
      req.response().setStatusCode(400).end();
    }
  }).listen(8080, ready -> {
    if (ready.failed()) {
      throw new RuntimeException(ready.cause());
    }
    // ready
    latch.countDown();
  });

  latch.await();
}
 
Example #25
Source File: KeycloakOAuthFactory.java    From apiman with Apache License 2.0 5 votes vote down vote up
public static AuthHandler create(Vertx vertx, Router router, VertxEngineConfig apimanConfig, JsonObject authConfig) {
    OAuth2FlowType flowType = toEnum(authConfig.getString("flowType"));
    String role = authConfig.getString("requiredRole");

    Objects.requireNonNull(flowType, String.format("flowType must be specified and valid. Flows: %s.", Arrays.asList(OAuth2FlowType.values())));
    Objects.requireNonNull(role, "requiredRole must be non-null.");

    if (flowType != OAuth2FlowType.AUTH_CODE) {
        return directGrant(vertx, apimanConfig, authConfig, flowType, role);
    } else {
        return standardAuth(vertx, router, apimanConfig, authConfig, flowType);
    }
}
 
Example #26
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 #27
Source File: OAuth2.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) {
    OAuth2ClientOptions credentials = new OAuth2ClientOptions(mapToJson(config));
    if (config.get("oauthUri") != null) {
        credentials.setSite(config.get("oauthUri"));
    }
    if (config.get("clientId") != null) {
        credentials.setClientID(config.get("clientId"));
    }

    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 = OAuth2Auth.create(vertx, flowType, credentials);

    oauth2.getToken(params, tokenResult -> {
      if (tokenResult.succeeded()) {
          log.debug("OAuth2 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 #28
Source File: AbstractOAuth2Base.java    From apiman with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("nls")
protected OAuth2FlowType getFlowType(String flowAsString) {
    switch(flowAsString.toUpperCase()) {
    case "AUTH_CODE":
    case "AUTHCODE":
        return OAuth2FlowType.AUTH_CODE;
    case "CLIENT":
        return OAuth2FlowType.CLIENT;
    case "PASSWORD":
        return OAuth2FlowType.PASSWORD;
    }
    throw new OAuth2Exception("Unrecognised OAuth2FlowType " + flowAsString);
}
 
Example #29
Source File: WikiServer.java    From redpipe with Apache License 2.0 5 votes vote down vote up
@Override
protected AuthProvider setupAuthenticationRoutes() {
	JsonObject keycloackConfig = AppGlobals.get().getConfig().getJsonObject("keycloack");
	OAuth2Auth authWeb = KeycloakAuth.create(AppGlobals.get().getVertx(), keycloackConfig);
	OAuth2Auth authApi = KeycloakAuth.create(AppGlobals.get().getVertx(), OAuth2FlowType.PASSWORD, keycloackConfig);
	
	// FIXME: URL
	OAuth2AuthHandler authHandler = OAuth2AuthHandler.create((OAuth2Auth) authWeb, "http://localhost:9000/callback");
	Router router = AppGlobals.get().getRouter();
	// FIXME: crazy!!
	AuthProvider authProvider = AuthProvider.newInstance(authWeb.getDelegate());
	router.route().handler(UserSessionHandler.create(authProvider));

	authHandler.setupCallback(router.get("/callback"));
	
	JWTAuth jwtAuth = JWTAuth.create(AppGlobals.get().getVertx(), new JWTAuthOptions(new JsonObject()
			.put("keyStore", AppGlobals.get().getConfig().getJsonObject("keystore"))));
	AppGlobals.get().setGlobal(JWTAuth.class, jwtAuth);
	
	JWTAuthHandler jwtAuthHandler = JWTAuthHandler.create(jwtAuth, "/wiki/api/token");

	// FIXME: just use different routers
	router.route().handler(ctx -> {
		if(!ctx.request().uri().startsWith("/wiki/api/"))
			authHandler.handle(ctx);
		else
			jwtAuthHandler.handle(ctx);
	});
	
	return AuthProvider.newInstance(authApi.getDelegate());
}
 
Example #30
Source File: MailchimpAuth.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Create a OAuth2Auth provider for Mailchimp
 *
 * @param clientId          the client id given to you by Mailchimp
 * @param clientSecret      the client secret given to you by Mailchimp
 * @param httpClientOptions custom http client options
 */
static OAuth2Auth create(Vertx vertx, String clientId, String clientSecret, HttpClientOptions httpClientOptions) {
  return
    OAuth2Auth.create(vertx, new OAuth2Options()
      .setHttpClientOptions(httpClientOptions)
      .setFlow(OAuth2FlowType.AUTH_CODE)
      .setClientID(clientId)
      .setClientSecret(clientSecret)
      .setSite("https://login.mailchimp.com")
      .setTokenPath("/oauth2/token")
      .setAuthorizationPath("/oauth2/authorize")
      .setUserInfoPath("/oauth2/metadata"));
}