Search in sources :

Example 11 with AccessToken

use of org.glassfish.jersey.client.oauth1.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 12 with AccessToken

use of org.glassfish.jersey.client.oauth1.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 13 with AccessToken

use of org.glassfish.jersey.client.oauth1.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 14 with AccessToken

use of org.glassfish.jersey.client.oauth1.AccessToken in project vertx-auth by vert-x3.

the class OAuth2IntrospectTest method introspectAccessToken.

@Test
public void introspectAccessToken() {
    config = oauthIntrospect;
    fixture = fixtureIntrospect;
    oauth2.introspectToken(token, res -> {
        if (res.failed()) {
            fail(res.cause().getMessage());
        } else {
            AccessToken token = res.result();
            assertNotNull(token);
            JsonObject principal = token.principal();
            // clean time specific value
            principal.remove("expires_at");
            principal.remove("access_token");
            final JsonObject assertion = fixtureIntrospect.copy();
            assertEquals(assertion.getMap(), principal.getMap());
            token.isAuthorized("scopeB", res0 -> {
                if (res0.failed()) {
                    fail(res0.cause().getMessage());
                } else {
                    if (res0.result()) {
                        testComplete();
                    } else {
                        fail("Should be allowed");
                    }
                }
            });
        }
    });
    await();
}
Also used : AccessToken(io.vertx.ext.auth.oauth2.AccessToken) JsonObject(io.vertx.core.json.JsonObject) Test(org.junit.Test)

Example 15 with AccessToken

use of org.glassfish.jersey.client.oauth1.AccessToken in project vertx-auth by vert-x3.

the class OAuth2UserInfoTest method getUserInfo.

@Test
public void getUserInfo() {
    final AccessToken accessToken = new OAuth2TokenImpl((OAuth2AuthProviderImpl) oauth2, new JsonObject("{\"access_token\":\"eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJhdXRob3JpemF0aW9uIjp7InBlcm1pc3Npb25zIjpbeyJyZXNvdXJjZV9zZXRfaWQiOiJkMmZlOTg0My02NDYyLTRiZmMtYmFiYS1iNTc4N2JiNmUwZTciLCJyZXNvdXJjZV9zZXRfbmFtZSI6IkhlbGxvIFdvcmxkIFJlc291cmNlIn1dfSwianRpIjoiZDYxMDlhMDktNzhmZC00OTk4LWJmODktOTU3MzBkZmQwODkyLTE0NjQ5MDY2Nzk0MDUiLCJleHAiOjk5OTk5OTk5OTksIm5iZiI6MCwiaWF0IjoxNDY0OTA2NjcxLCJzdWIiOiJmMTg4OGY0ZC01MTcyLTQzNTktYmUwYy1hZjMzODUwNWQ4NmMiLCJ0eXAiOiJrY19ldHQiLCJhenAiOiJoZWxsby13b3JsZC1hdXRoei1zZXJ2aWNlIn0\",\"active\":true,\"scope\":\"scopeA scopeB\",\"client_id\":\"client-id\",\"username\":\"username\",\"token_type\":\"bearer\",\"expires_at\":99999999999000}"));
    accessToken.userInfo(userInfo -> {
        if (userInfo.failed()) {
            fail(userInfo.cause().getMessage());
        } else {
            testComplete();
        }
    });
    await();
}
Also used : AccessToken(io.vertx.ext.auth.oauth2.AccessToken) JsonObject(io.vertx.core.json.JsonObject) OAuth2TokenImpl(io.vertx.ext.auth.oauth2.impl.OAuth2TokenImpl) Test(org.junit.Test)

Aggregations

AccessToken (com.google.auth.oauth2.AccessToken)71 Test (org.junit.Test)41 GoogleCredentials (com.google.auth.oauth2.GoogleCredentials)29 Date (java.util.Date)22 IOException (java.io.IOException)19 AccessToken (io.vertx.ext.auth.oauth2.AccessToken)16 Client (javax.ws.rs.client.Client)10 AccessToken (org.glassfish.jersey.client.oauth1.AccessToken)10 ConsumerCredentials (org.glassfish.jersey.client.oauth1.ConsumerCredentials)10 JsonObject (io.vertx.core.json.JsonObject)9 URI (java.net.URI)9 Feature (javax.ws.rs.core.Feature)8 JerseyTest (org.glassfish.jersey.test.JerseyTest)8 MockHttpTransport (com.google.api.client.testing.http.MockHttpTransport)6 InputStreamReader (java.io.InputStreamReader)6 Instant (java.time.Instant)6 WebTarget (javax.ws.rs.client.WebTarget)6 LoggingFeature (org.glassfish.jersey.logging.LoggingFeature)6 OAuth2Credentials (com.google.auth.oauth2.OAuth2Credentials)5 OAuth2TokenImpl (io.vertx.ext.auth.oauth2.impl.OAuth2TokenImpl)5