Search in sources :

Example 26 with AccessToken

use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project jersey by jersey.

the class OauthClientAuthorizationFlowTest method testOAuthClientFlow.

@Test
public void testOAuthClientFlow() throws Exception {
    final String uri = getBaseUri().toString();
    final OAuth1AuthorizationFlow authFlow = OAuth1ClientSupport.builder(new ConsumerCredentials("dpf43f3p2l4k3l03", "kd94hf93k423kf44")).timestamp("1191242090").nonce("hsu94j3884jdopsl").signatureMethod("PLAINTEXT").authorizationFlow(uri + "request_token", uri + "access_token", uri + "authorize").enableLogging().build();
    // Check we have correct authorization URI.
    final String authorizationUri = authFlow.start();
    assertThat(authorizationUri, containsString("authorize?oauth_token=hh5s93j4hdidpola"));
    // For the purpose of the test I need parameters (and there is no way how to do it now).
    final Field paramField = authFlow.getClass().getDeclaredField("parameters");
    paramField.setAccessible(true);
    final OAuth1Parameters params = (OAuth1Parameters) paramField.get(authFlow);
    // Update parameters.
    params.timestamp("1191242092").nonce("dji430splmx33448");
    final AccessToken accessToken = authFlow.finish();
    assertThat(accessToken, equalTo(new AccessToken("nnch734d00sl2jdk", "pfkkdhi9sl3r4s00")));
    // Update parameters before creating a feature (i.e. changing signature method).
    params.nonce("kllo9940pd9333jh").signatureMethod("HMAC-SHA1").timestamp("1191242096");
    // Check Authorized Client.
    final Client flowClient = authFlow.getAuthorizedClient().register(LoggingFeature.class);
    String responseEntity = flowClient.target(uri).path("/photos").queryParam("file", "vacation.jpg").queryParam("size", "original").request().get(String.class);
    assertThat("Flow Authorized Client", responseEntity, equalTo("PHOTO"));
    // Check Feature.
    final Client featureClient = ClientBuilder.newClient().register(authFlow.getOAuth1Feature()).register(LoggingFeature.class);
    responseEntity = featureClient.target(uri).path("/photos").queryParam("file", "vacation.jpg").queryParam("size", "original").request().get(String.class);
    assertThat("Feature Client", responseEntity, equalTo("PHOTO"));
}
Also used : OAuth1AuthorizationFlow(org.glassfish.jersey.client.oauth1.OAuth1AuthorizationFlow) Field(java.lang.reflect.Field) OAuth1Parameters(org.glassfish.jersey.oauth1.signature.OAuth1Parameters) ConsumerCredentials(org.glassfish.jersey.client.oauth1.ConsumerCredentials) AccessToken(org.glassfish.jersey.client.oauth1.AccessToken) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Client(javax.ws.rs.client.Client) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Example 27 with AccessToken

use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project helios by spotify.

the class AuthenticatingHttpConnectorTest method createAuthenticatingConnectorWithCertFile.

private AuthenticatingHttpConnector createAuthenticatingConnectorWithCertFile() {
    final EndpointIterator endpointIterator = EndpointIterator.of(endpoints);
    final CertKeyPaths clientCertificatePath = CertKeyPaths.create(CERTIFICATE_PATH, KEY_PATH);
    return new AuthenticatingHttpConnector(USER, Suppliers.ofInstance(Optional.<AccessToken>absent()), Optional.<AgentProxy>absent(), Optional.of(clientCertificatePath), endpointIterator, connector);
}
Also used : AccessToken(com.google.auth.oauth2.AccessToken) CertKeyPaths(com.spotify.sshagenttls.CertKeyPaths)

Example 28 with AccessToken

use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project java by kubernetes-client.

the class GCPAuthenticatorTest method testRefreshApplicationDefaultCredentials.

@Test
public void testRefreshApplicationDefaultCredentials() {
    Date fakeTokenExpiryDate = Date.from(Instant.parse(fakeTokenExpiry));
    Mockito.when(mockGC.getAccessToken()).thenReturn(new AccessToken(fakeToken, fakeTokenExpiryDate));
    final Map<String, Object> config = new HashMap<String, Object>() {
    };
    final Map<String, Object> result = gcpAuthenticator.refresh(config);
    assertEquals(fakeToken, result.get(GCPAuthenticator.ACCESS_TOKEN));
    assertEquals(fakeTokenExpiryDate, result.get(GCPAuthenticator.EXPIRY));
}
Also used : HashMap(java.util.HashMap) AccessToken(com.google.auth.oauth2.AccessToken) Date(java.util.Date) Test(org.junit.Test)

Example 29 with AccessToken

use of com.microsoft.identity.common.internal.providers.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 30 with AccessToken

use of com.microsoft.identity.common.internal.providers.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)

Aggregations

AccessToken (com.google.auth.oauth2.AccessToken)78 Test (org.junit.Test)44 GoogleCredentials (com.google.auth.oauth2.GoogleCredentials)33 Date (java.util.Date)23 IOException (java.io.IOException)20 AccessToken (io.vertx.ext.auth.oauth2.AccessToken)16 Instant (java.time.Instant)10 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 ServiceAccountCredentials (com.google.auth.oauth2.ServiceAccountCredentials)6 Credential (io.cdap.cdap.proto.security.Credential)6 InputStreamReader (java.io.InputStreamReader)6 Clock (java.time.Clock)6 WebTarget (javax.ws.rs.client.WebTarget)6