Search in sources :

Example 21 with AccessToken

use of io.vertx.ext.auth.oauth2.AccessToken in project java by kubernetes-client.

the class GCPAuthenticator method refresh.

@Override
public Map<String, Object> refresh(Map<String, Object> config) {
    if (isCmd(config)) {
        return refreshCmd(config);
    }
    // Google Application Credentials-based refresh
    // https://cloud.google.com/kubernetes-engine/docs/how-to/api-server-authentication#environments-without-gcloud
    String[] scopes = parseScopes(config);
    try {
        if (this.gc == null)
            this.gc = GoogleCredentials.getApplicationDefault().createScoped(scopes);
        AccessToken accessToken = gc.getAccessToken();
        config.put(ACCESS_TOKEN, accessToken.getTokenValue());
        config.put(EXPIRY, accessToken.getExpirationTime());
        return config;
    } catch (IOException e) {
        throw new RuntimeException("The Application Default Credentials are not available.", e);
    }
}
Also used : AccessToken(com.google.auth.oauth2.AccessToken) IOException(java.io.IOException)

Example 22 with AccessToken

use of io.vertx.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
        JsonObject data = new JsonObject().put("client_id", CLIENT_ID);
        // and now delegate to the engine to render it.
        engine.render(data, "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
                        JsonObject data = new JsonObject().put("userInfo", userInfo);
                        // and now delegate to the engine to render it.
                        engine.render(data, "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).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 23 with AccessToken

use of io.vertx.ext.auth.oauth2.AccessToken in project curiostack by curioswitch.

the class AbstractAccessTokenProvider method refresh.

private CompletableFuture<AccessToken> refresh(Type type) {
    return fetchToken(type).handle((msg, t) -> {
        if (t != null) {
            throw new IllegalStateException("Failed to refresh GCP access token.", t);
        }
        final TokenResponse response;
        try {
            response = OBJECT_MAPPER.readValue(msg.content().array(), TokenResponse.class);
        } catch (IOException e) {
            throw new UncheckedIOException("Error parsing token refresh response.", e);
        }
        long expiresAtMilliseconds = clock.millis() + TimeUnit.SECONDS.toMillis(response.expiresIn());
        return new AccessToken(type == Type.ID_TOKEN ? response.idToken() : response.accessToken(), new Date(expiresAtMilliseconds));
    });
}
Also used : AccessToken(com.google.auth.oauth2.AccessToken) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) Date(java.util.Date)

Example 24 with AccessToken

use of io.vertx.ext.auth.oauth2.AccessToken in project grpc-java by grpc.

the class GoogleAuthLibraryCallCredentialsTest method serviceAccountWithScopeNotToJwt.

@Test
public void serviceAccountWithScopeNotToJwt() throws Exception {
    final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
    KeyPair pair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
    ServiceAccountCredentials credentials = new ServiceAccountCredentials(null, "email@example.com", pair.getPrivate(), null, Arrays.asList("somescope")) {

        @Override
        public AccessToken refreshAccessToken() {
            return token;
        }
    };
    GoogleAuthLibraryCallCredentials callCredentials = new GoogleAuthLibraryCallCredentials(credentials);
    callCredentials.applyRequestMetadata(method, attrs, executor, applier);
    assertEquals(1, runPendingRunnables());
    verify(applier).apply(headersCaptor.capture());
    Metadata headers = headersCaptor.getValue();
    Iterable<String> authorization = headers.getAll(AUTHORIZATION);
    assertArrayEquals(new String[] { "Bearer allyourbase" }, Iterables.toArray(authorization, String.class));
}
Also used : KeyPair(java.security.KeyPair) AccessToken(com.google.auth.oauth2.AccessToken) Metadata(io.grpc.Metadata) ServiceAccountCredentials(com.google.auth.oauth2.ServiceAccountCredentials) Date(java.util.Date) Test(org.junit.Test)

Example 25 with AccessToken

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

the class ContainerRegistryAuthSupplier method authFor.

@Override
public RegistryAuth authFor(final String imageName) throws DockerException {
    final String[] imageParts = imageName.split("/", 2);
    if (imageParts.length < 2 || !GCR_REGISTRIES.contains(imageParts[0])) {
        // not an image on GCR
        return null;
    }
    final AccessToken accessToken;
    try {
        accessToken = getAccessToken();
    } catch (IOException e) {
        throw new DockerException(e);
    }
    return authForAccessToken(accessToken);
}
Also used : DockerException(com.spotify.docker.client.exceptions.DockerException) AccessToken(com.google.auth.oauth2.AccessToken) IOException(java.io.IOException)

Aggregations

Test (org.junit.Test)25 AccessToken (com.google.auth.oauth2.AccessToken)22 JsonObject (io.vertx.core.json.JsonObject)13 AccessToken (io.vertx.ext.auth.oauth2.AccessToken)13 Date (java.util.Date)10 IOException (java.io.IOException)9 OAuth2TokenImpl (io.vertx.ext.auth.oauth2.impl.OAuth2TokenImpl)8 GoogleCredentials (com.google.auth.oauth2.GoogleCredentials)7 OAuth2Credentials (com.google.auth.oauth2.OAuth2Credentials)5 OAuth2Response (io.vertx.ext.auth.oauth2.OAuth2Response)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 Feature (javax.ws.rs.core.Feature)4 JerseyTest (org.glassfish.jersey.test.JerseyTest)4 ServiceAccountCredentials (com.google.auth.oauth2.ServiceAccountCredentials)3 Buffer (io.vertx.core.buffer.Buffer)3 URI (java.net.URI)3 WebTarget (javax.ws.rs.client.WebTarget)3