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

The following examples show how to use io.vertx.ext.auth.oauth2.OAuth2Auth. 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: OAuth2AuthHandlerImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
public OAuth2AuthHandlerImpl(Vertx vertx, OAuth2Auth authProvider, String callbackURL) {
  super(authProvider, Type.BEARER);
  // get a reference to the prng
  this.prng = VertxContextPRNG.current(vertx);

  try {
    if (callbackURL != null) {
      final URL url = new URL(callbackURL);
      this.host = url.getProtocol() + "://" + url.getHost() + (url.getPort() == -1 ? "" : ":" + url.getPort());
      this.callbackPath = url.getPath();
    } else {
      this.host = null;
      this.callbackPath = null;
    }
  } catch (MalformedURLException e) {
    throw new RuntimeException(e);
  }
}
 
Example #2
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 #3
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 #4
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 #5
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 #6
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 #7
Source File: OAuth2AuthHandlerImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private String authURI(String redirectURL, String state) {
  final JsonObject config = new JsonObject()
    .put("state", state != null ? state : redirectURL);

  if (host != null) {
    config.put("redirect_uri", host + callback.getPath());
  }

  if (scopes.size() > 0) {
    config.put("scopes", scopes);
  }

  if (prompt != null) {
    config.put("prompt", prompt);
  }

  if (extraParams != null) {
    config.mergeIn(extraParams);
  }

  return ((OAuth2Auth) authProvider).authorizeURL(config);
}
 
Example #8
Source File: OIDCTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Ignore
@Test
public void testDecode() {
  OpenIDConnectAuth.discover(
    vertx,
    new OAuth2Options()
      .setClientID("vertx")
      .setSite("http://localhost:8080/auth/realms/master"),
    res -> {
      if (res.failed()) {
        fail(res.cause());
        return;
      }

      final OAuth2Auth oidc = res.result();

      oidc.decodeToken("borked", res1 -> {
        if (res1.failed()) {
          testComplete();
          return;
        }
        fail("Should not reach this!");
      });
    });
  await();
}
 
Example #9
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 #10
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 #11
Source File: CustomRouterConfig.java    From vxms with Apache License 2.0 6 votes vote down vote up
@Override
public void customRouteConfiguration(Vertx vertx, Router router, boolean secure, String host, int port) {
    final JsonObject config = vertx.getOrCreateContext().config();
    final OAuth2Auth authProvider = GithubAuth
        .create(vertx,config.getString("clientID"),config.getString("clientSecret"));
    // store authentication
    router.route().handler(UserSessionHandler.create(authProvider));

    final String hostURI = (secure ? "https://" : "http://") + host + ":" + port;
    final String callbackURI = hostURI+"/callback";

    final OAuth2AuthHandler oauth2 = OAuth2AuthHandler.create(authProvider, callbackURI);

    // setup the callback handler for receiving the GitHub callback
    oauth2.setupCallback(router.route());

    // Serve the static private pages from directory 'private'
    router.route("/private/*").handler(oauth2);

    router.get("/").handler(ctx ->
            ctx.
                    response().
                    putHeader("content-type", "text/html").
                    end("Hello <br><a href=\"/private/\">Protected by Github</a>"));
}
 
Example #12
Source File: APIGatewayVerticle.java    From vertx-blueprint-microservice with Apache License 2.0 6 votes vote down vote up
private void authCallback(OAuth2Auth oauth2, String hostURL, RoutingContext context) {
  final String code = context.request().getParam("code");
  // code is a require value
  if (code == null) {
    context.fail(400);
    return;
  }
  final String redirectTo = context.request().getParam("redirect_uri");
  final String redirectURI = hostURL + context.currentRoute().getPath() + "?redirect_uri=" + redirectTo;
  oauth2.getToken(new JsonObject().put("code", code).put("redirect_uri", redirectURI), ar -> {
    if (ar.failed()) {
      logger.warn("Auth fail");
      context.fail(ar.cause());
    } else {
      logger.info("Auth success");
      context.setUser(ar.result());
      context.response()
        .putHeader("Location", redirectTo)
        .setStatusCode(302)
        .end();
    }
  });
}
 
Example #13
Source File: AzureADAuth.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
/**
 * Create a OAuth2Auth provider for OpenID Connect Discovery. The discovery will use the default site in the
 * configuration options and attempt to load the well known descriptor. If a site is provided (for example when
 * running on a custom instance) that site will be used to do the lookup.
 * <p>
 * If the discovered config includes a json web key url, it will be also fetched and the JWKs will be loaded
 * into the OAuth provider so tokens can be decoded.
 * <p>
 * With this provider, if the given configuration is using the flow type {@link OAuth2FlowType#AUTH_JWT} then
 * the extra parameters object will include {@code requested_token_use = on_behalf_of} as required by
 * <a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/v1-oauth2-on-behalf-of-flow">https://docs.microsoft.com/en-us/azure/active-directory</a>.
 *
 * @param vertx   the vertx instance
 * @param config  the initial config
 * @param handler the instantiated Oauth2 provider instance handler
 */
static void discover(final Vertx vertx, final OAuth2Options config, final Handler<AsyncResult<OAuth2Auth>> handler) {
  // don't override if already set
  final String site = config.getSite() == null ? "https://login.windows.net/common" : config.getSite();

  final JsonObject extraParameters = new JsonObject().put("resource", "{tenant}");

  if (config.getFlow() != null && AUTH_JWT == config.getFlow()) {
    // this is a "on behalf of" mode
    extraParameters.put("requested_token_use", "on_behalf_of");
  }

  OpenIDConnectAuth.discover(
    vertx,
    new OAuth2Options(config)
      // Azure OpenId does not return the same url where the request was sent to
      .setValidateIssuer(false)
      .setSite(site)
      .setScopeSeparator(",")
      .setExtraParameters(extraParameters),
    handler);
}
 
Example #14
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 #15
Source File: WebExamples.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public void example61(Vertx vertx, Router router, OAuth2Auth provider) {
  // create a oauth2 handler pinned to
  // myserver.com: "https://myserver.com:8447/callback"
  OAuth2AuthHandler oauth2 = OAuth2AuthHandler
    .create(vertx, provider, "https://myserver.com:8447/callback");

  // now allow the handler to setup the callback url for you
  oauth2.setupCallback(router.route());
}
 
Example #16
Source File: WebExamples.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public void example58(Vertx vertx, Router router) {

    // create an OAuth2 provider, clientID and clientSecret
    // should be requested to github
    OAuth2Auth authProvider = GithubAuth
      .create(vertx, "CLIENT_ID", "CLIENT_SECRET");

    // create a oauth2 handler on our running server
    // the second argument is the full url to the
    // callback as you entered in your provider management console.
    OAuth2AuthHandler oauth2 = OAuth2AuthHandler
      .create(vertx, authProvider, "https://myserver.com/callback");

    // setup the callback handler for receiving the GitHub callback
    oauth2.setupCallback(router.route());

    // protect everything under /protected
    router.route("/protected/*").handler(oauth2);
    // mount some handler under the protected zone
    router
      .route("/protected/somepage")
      .handler(ctx -> ctx.response().end("Welcome to the protected resource!"));

    // welcome page
    router
      .get("/")
      .handler(ctx -> ctx.response()
        .putHeader("content-type", "text/html")
        .end("Hello<br><a href=\"/protected/somepage\">Protected by Github</a>"));
  }
 
Example #17
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 #18
Source File: InstagramAuth.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Create a OAuth2Auth provider for Instagram
 *
 * @param clientId          the client id given to you by Instagram
 * @param clientSecret      the client secret given to you by Instagram
 * @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.instagram.com")
      .setTokenPath("/oauth/access_token")
      .setAuthorizationPath("/oauth/authorize")
      .setUserInfoPath("/v1/users/self")
      .setScopeSeparator(" "));
}
 
Example #19
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 #20
Source File: OAuth2UserInfoTest.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, oauthConfig);

  final CountDownLatch latch = new CountDownLatch(1);

  server = vertx.createHttpServer().requestHandler(req -> {
    if (req.method() == HttpMethod.GET && "/oauth/userinfo".equals(req.path())) {
      assertTrue(req.getHeader("Authorization").contains("Bearer "));

      try {
        assertEquals(googleParams, queryToJSON(req.query()));
      } 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: WebExamples.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public void example59(Vertx vertx, Router router) {

    // create an OAuth2 provider, clientID and clientSecret
    // should be requested to Google
    OAuth2Auth authProvider = OAuth2Auth.create(vertx, new OAuth2Options()
      .setClientID("CLIENT_ID")
      .setClientSecret("CLIENT_SECRET")
      .setFlow(OAuth2FlowType.AUTH_CODE)
      .setSite("https://accounts.google.com")
      .setTokenPath("https://www.googleapis.com/oauth2/v3/token")
      .setAuthorizationPath("/o/oauth2/auth"));

    // create a oauth2 handler on our domain: "http://localhost:8080"
    OAuth2AuthHandler oauth2 = OAuth2AuthHandler
      .create(vertx, authProvider, "http://localhost:8080");

    // these are the scopes
    oauth2.withScope("profile");

    // setup the callback handler for receiving the Google callback
    oauth2.setupCallback(router.get("/callback"));

    // protect everything under /protected
    router.route("/protected/*").handler(oauth2);
    // mount some handler under the protected zone
    router
      .route("/protected/somepage")
      .handler(ctx -> ctx.response().end("Welcome to the protected resource!"));

    // welcome page
    router
      .get("/")
      .handler(ctx -> ctx.response()
        .putHeader("content-type", "text/html")
        .end("Hello<br><a href=\"/protected/somepage\">Protected by Google</a>"));
  }
 
Example #22
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"));
}
 
Example #23
Source File: HerokuAuth.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Create a OAuth2Auth provider for Heroku
 *
 * @param clientId          the client id given to you by Heroku
 * @param clientSecret      the client secret given to you by Heroku
 * @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://id.heroku.com")
      .setTokenPath("/oauth/token")
      .setAuthorizationPath("/oauth/authorize")
      .setScopeSeparator(" "));
}
 
Example #24
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 #25
Source File: LiveAuth.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Create a OAuth2Auth provider for live.com
 *
 * @param clientId          the client id given to you by live.com
 * @param clientSecret      the client secret given to you by live.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://login.live.com")
      .setTokenPath("/oauth20_token.srf")
      .setAuthorizationPath("/oauth20_authorize.srf")
      .setScopeSeparator(" "));
}
 
Example #26
Source File: LinkedInAuth.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Create a OAuth2Auth provider for LinkedIn
 *
 * @param clientId          the client id given to you by LinkedIn
 * @param clientSecret      the client secret given to you by LinkedIn
 * @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://www.linkedin.com")
      .setTokenPath("/oauth/v2/accessToken")
      .setAuthorizationPath("/oauth/v2/authorization")
      .setUserInfoPath("/people/~")
      .setScopeSeparator(" "));
}
 
Example #27
Source File: CloudFoundryAuth.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Create a OAuth2Auth provider for CloudFoundry UAA
 *
 * @param clientId          the client id given to you by CloudFoundry UAA
 * @param clientSecret      the client secret given to you by CloudFoundry UAA
 * @param uuaURL            the url to your UUA server instance
 * @param httpClientOptions custom http client options
 */
static OAuth2Auth create(Vertx vertx, String clientId, String clientSecret, String uuaURL, HttpClientOptions httpClientOptions) {
  return
    OAuth2Auth.create(vertx, new OAuth2Options()
      .setHttpClientOptions(httpClientOptions)
      .setFlow(OAuth2FlowType.AUTH_CODE)
      .setClientID(clientId)
      .setClientSecret(clientSecret)
      .setSite(uuaURL)
      .setTokenPath("/oauth/token")
      .setAuthorizationPath("/oauth/authorize")
      .setScopeSeparator(" "));
}
 
Example #28
Source File: GoogleAuth.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Create a OAuth2Auth provider for OpenID Connect Discovery. The discovery will use the default site in the
 * configuration options and attempt to load the well known descriptor. If a site is provided (for example when
 * running on a custom instance) that site will be used to do the lookup.
 * <p>
 * If the discovered config includes a json web key url, it will be also fetched and the JWKs will be loaded
 * into the OAuth provider so tokens can be decoded.
 *
 * @param vertx   the vertx instance
 * @param config  the initial config
 * @param handler the instantiated Oauth2 provider instance handler
 */
static void discover(final Vertx vertx, final OAuth2Options config, final Handler<AsyncResult<OAuth2Auth>> handler) {
  // don't override if already set
  final String site = config.getSite() == null ? "https://accounts.google.com" : config.getSite();

  OpenIDConnectAuth.discover(
    vertx,
    new OAuth2Options(config)
      .setSite(site)
      .setUserInfoParameters(new JsonObject()
        .put("alt", "json"))
      .setScopeSeparator(" "),
    handler);
}
 
Example #29
Source File: OAuth2KeyRotationTest.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadJWK() {
  OAuth2Auth oauth2 = GoogleAuth.create(vertx, "", "");

  oauth2.jWKSet(load -> {
    assertFalse(load.failed());
    testComplete();
  });
  await();
}
 
Example #30
Source File: FacebookAuth.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Create a OAuth2Auth provider for Facebook
 *
 * @param clientId          the client id given to you by Facebook
 * @param clientSecret      the client secret given to you by Facebook
 * @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://www.facebook.com")
      .setTokenPath("https://graph.facebook.com/oauth/access_token")
      .setAuthorizationPath("/dialog/oauth")
      .setUserInfoPath("https://graph.facebook.com/me")
      .setScopeSeparator(","));
}