Search in sources :

Example 6 with AccessToken

use of io.vertx.reactivex.ext.auth.oauth2.AccessToken in project vertx-examples by vert-x3.

the class Server method start.

@Override
public void start() throws Exception {
    // To simplify the development of the web components we use a Router to route all HTTP requests
    // to organize our code in a reusable way.
    final Router router = Router.router(vertx);
    // We need cookies and sessions
    router.route().handler(CookieHandler.create());
    router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx)));
    // Simple auth service which uses a GitHub to authenticate the user
    OAuth2Auth authProvider = GithubAuth.create(vertx, CLIENT_ID, CLIENT_SECRET);
    // We need a user session handler too to make sure the user is stored in the session between requests
    router.route().handler(UserSessionHandler.create(authProvider));
    // we now protect the resource under the path "/protected"
    router.route("/protected").handler(OAuth2AuthHandler.create(authProvider).setupCallback(router.route("/callback")).addAuthority("user:email"));
    // Entry point to the application, this will render a custom template.
    router.get("/").handler(ctx -> {
        // we pass the client id to the template
        ctx.put("client_id", CLIENT_ID);
        // and now delegate to the engine to render it.
        engine.render(ctx, "views", "/index.hbs", res -> {
            if (res.succeeded()) {
                ctx.response().putHeader("Content-Type", "text/html").end(res.result());
            } else {
                ctx.fail(res.cause());
            }
        });
    });
    // The protected resource
    router.get("/protected").handler(ctx -> {
        AccessToken user = (AccessToken) ctx.user();
        // retrieve the user profile, this is a common feature but not from the official OAuth2 spec
        user.userInfo(res -> {
            if (res.failed()) {
                // request didn't succeed because the token was revoked so we
                // invalidate the token stored in the session and render the
                // index page so that the user can start the OAuth flow again
                ctx.session().destroy();
                ctx.fail(res.cause());
            } else {
                // the request succeeded, so we use the API to fetch the user's emails
                final JsonObject userInfo = res.result();
                // fetch the user emails from the github API
                // the fetch method will retrieve any resource and ensure the right
                // secure headers are passed.
                user.fetch("https://api.github.com/user/emails", res2 -> {
                    if (res2.failed()) {
                        // request didn't succeed because the token was revoked so we
                        // invalidate the token stored in the session and render the
                        // index page so that the user can start the OAuth flow again
                        ctx.session().destroy();
                        ctx.fail(res2.cause());
                    } else {
                        userInfo.put("private_emails", res2.result().jsonArray());
                        // we pass the client info to the template
                        ctx.put("userInfo", userInfo);
                        // and now delegate to the engine to render it.
                        engine.render(ctx, "views", "/advanced.hbs", res3 -> {
                            if (res3.succeeded()) {
                                ctx.response().putHeader("Content-Type", "text/html").end(res3.result());
                            } else {
                                ctx.fail(res3.cause());
                            }
                        });
                    }
                });
            }
        });
    });
    vertx.createHttpServer().requestHandler(router::accept).listen(8080);
}
Also used : AccessToken(io.vertx.ext.auth.oauth2.AccessToken) Router(io.vertx.ext.web.Router) JsonObject(io.vertx.core.json.JsonObject) OAuth2Auth(io.vertx.ext.auth.oauth2.OAuth2Auth)

Example 7 with AccessToken

use of io.vertx.reactivex.ext.auth.oauth2.AccessToken in project docker-client by spotify.

the class ContainerRegistryAuthSupplier method authForBuild.

@Override
public RegistryConfigs authForBuild() throws DockerException {
    final AccessToken accessToken;
    try {
        accessToken = getAccessToken();
    } catch (IOException e) {
        // do not fail as the GCR access token may not be necessary for building the image currently
        // being built
        log.warn("unable to get access token for Google Container Registry, " + "configuration for building image will not contain RegistryAuth for GCR", e);
        return RegistryConfigs.empty();
    }
    final Map<String, RegistryAuth> configs = new HashMap<>(GCR_REGISTRIES.size());
    for (String serverName : GCR_REGISTRIES) {
        configs.put(serverName, authForAccessToken(accessToken));
    }
    return RegistryConfigs.create(configs);
}
Also used : HashMap(java.util.HashMap) AccessToken(com.google.auth.oauth2.AccessToken) IOException(java.io.IOException) RegistryAuth(com.spotify.docker.client.messages.RegistryAuth)

Example 8 with AccessToken

use of io.vertx.reactivex.ext.auth.oauth2.AccessToken in project docker-client by spotify.

the class ContainerRegistryAuthSupplierTest method testAuthForBuild_TokenWithoutExpirationDoesNotCauseRefresh.

@Test
public void testAuthForBuild_TokenWithoutExpirationDoesNotCauseRefresh() throws Exception {
    final AccessToken accessToken = new AccessToken(tokenValue, null);
    final GoogleCredentials credentials = new GoogleCredentials(accessToken);
    final ContainerRegistryAuthSupplier supplier = new ContainerRegistryAuthSupplier(credentials, clock, TimeUnit.SECONDS.toMillis(minimumExpirationSecs), refresher);
    final RegistryConfigs configs = supplier.authForBuild();
    assertThat(configs.configs().values(), is(not(empty())));
    assertThat(configs.configs().values(), everyItem(matchesAccessToken(accessToken)));
    verify(refresher, never()).refresh(credentials);
}
Also used : RegistryConfigs(com.spotify.docker.client.messages.RegistryConfigs) AccessToken(com.google.auth.oauth2.AccessToken) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials) Test(org.junit.Test)

Example 9 with AccessToken

use of io.vertx.reactivex.ext.auth.oauth2.AccessToken in project docker-client by spotify.

the class ContainerRegistryAuthSupplierTest method testAuthForSwarm_TokenWithoutExpirationDoesNotCauseRefresh.

@Test
public void testAuthForSwarm_TokenWithoutExpirationDoesNotCauseRefresh() throws Exception {
    final AccessToken accessToken = new AccessToken(tokenValue, null);
    final GoogleCredentials credentials = new GoogleCredentials(accessToken);
    final ContainerRegistryAuthSupplier supplier = new ContainerRegistryAuthSupplier(credentials, clock, TimeUnit.SECONDS.toMillis(minimumExpirationSecs), refresher);
    assertThat(supplier.authForSwarm(), matchesAccessToken(accessToken));
    verify(refresher, never()).refresh(credentials);
}
Also used : AccessToken(com.google.auth.oauth2.AccessToken) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials) Test(org.junit.Test)

Example 10 with AccessToken

use of io.vertx.reactivex.ext.auth.oauth2.AccessToken in project api-framework by vinscom.

the class LoadUserFromSessionRouteBuillder method handle.

public void handle(RoutingContext pRoutingContext) {
    Session session = pRoutingContext.session();
    if (session != null && getOAuth2Auth() != null) {
        JsonObject principal = session.get(FrameworkConstants.Session.PRINCIPAL);
        if (principal != null) {
            OAuth2AuthProviderImpl provider = (OAuth2AuthProviderImpl) getOAuth2Auth().getDelegate();
            try {
                OAuth2TokenImpl token = new OAuth2TokenImpl(provider, principal);
                pRoutingContext.setUser(new AccessToken(token));
            } catch (RuntimeException e) {
                getLog().error(e);
                pRoutingContext.fail(401);
                return;
            }
        }
    }
    pRoutingContext.next();
}
Also used : AccessToken(io.vertx.reactivex.ext.auth.oauth2.AccessToken) JsonObject(io.vertx.core.json.JsonObject) OAuth2AuthProviderImpl(io.vertx.ext.auth.oauth2.impl.OAuth2AuthProviderImpl) OAuth2TokenImpl(io.vertx.ext.auth.oauth2.impl.OAuth2TokenImpl) Session(io.vertx.reactivex.ext.web.Session)

Aggregations

Test (org.junit.Test)25 AccessToken (com.google.auth.oauth2.AccessToken)21 AccessToken (io.vertx.ext.auth.oauth2.AccessToken)13 Date (java.util.Date)9 JsonObject (io.vertx.core.json.JsonObject)8 IOException (java.io.IOException)8 GoogleCredentials (com.google.auth.oauth2.GoogleCredentials)7 OAuth2TokenImpl (io.vertx.ext.auth.oauth2.impl.OAuth2TokenImpl)7 OAuth2Credentials (com.google.auth.oauth2.OAuth2Credentials)5 Client (javax.ws.rs.client.Client)5 AccessToken (org.glassfish.jersey.client.oauth1.AccessToken)5 ConsumerCredentials (org.glassfish.jersey.client.oauth1.ConsumerCredentials)5 Metadata (io.grpc.Metadata)4 URI (java.net.URI)4 Feature (javax.ws.rs.core.Feature)4 JerseyTest (org.glassfish.jersey.test.JerseyTest)4 ServiceAccountCredentials (com.google.auth.oauth2.ServiceAccountCredentials)3 WebTarget (javax.ws.rs.client.WebTarget)3 Response (javax.ws.rs.core.Response)3 LoggingFeature (org.glassfish.jersey.logging.LoggingFeature)3