Search in sources :

Example 6 with AccessToken

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

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 7 with AccessToken

use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project jade-data-repo by DataBiosphere.

the class TestRunner method executeTestConfiguration.

void executeTestConfiguration() throws Exception {
    // specify any value overrides in the Helm chart, then deploy
    if (!config.server.skipDeployment) {
    // modifyHelmValuesAndDeploy();
    }
    // update any Kubernetes properties specified by the test configuration
    if (!config.server.skipKubernetes) {
        KubernetesClientUtils.buildKubernetesClientObject(config.server);
        modifyKubernetesPostDeployment();
    }
    // get an instance of the API client per test user
    for (TestUserSpecification testUser : config.testUsers) {
        ApiClient apiClient = new ApiClient();
        apiClient.setBasePath(config.server.uri);
        GoogleCredentials userCredential = AuthenticationUtils.getDelegatedUserCredential(testUser);
        AccessToken userAccessToken = AuthenticationUtils.getAccessToken(userCredential);
        apiClient.setAccessToken(userAccessToken.getTokenValue());
        apiClientsForUsers.put(testUser.name, apiClient);
    }
    // get an instance of each test script class
    for (TestScriptSpecification testScriptSpecification : config.testScripts) {
        try {
            TestScript testScriptInstance = testScriptSpecification.scriptClass.newInstance();
            // set the billing account for the test script to use
            testScriptInstance.setBillingAccount(config.billingAccount);
            // set any parameters specified by the configuration
            testScriptInstance.setParameters(testScriptSpecification.parameters);
            scripts.add(testScriptInstance);
        } catch (IllegalAccessException | InstantiationException niEx) {
            throw new IllegalArgumentException("Error calling constructor of TestScript class: " + testScriptSpecification.scriptClass.getName(), niEx);
        }
    }
    // call the setup method of each test script
    Exception setupExceptionThrown = callTestScriptSetups();
    if (setupExceptionThrown != null) {
        // ignore any exceptions thrown by cleanup methods
        callTestScriptCleanups();
        throw new RuntimeException("Error calling test script setup methods.", setupExceptionThrown);
    }
    // for each test script
    List<ApiClient> apiClientList = new ArrayList<>(apiClientsForUsers.values());
    for (int tsCtr = 0; tsCtr < scripts.size(); tsCtr++) {
        TestScript testScript = scripts.get(tsCtr);
        TestScriptSpecification testScriptSpecification = config.testScripts.get(tsCtr);
        // add a description to the user journey threads/results that includes any parameters
        String userJourneyDescription = testScriptSpecification.name;
        if (testScriptSpecification.parameters != null) {
            userJourneyDescription += ": " + String.join(",", testScriptSpecification.parameters);
        }
        // create a thread pool for running its user journeys
        ThreadPoolExecutor threadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(testScriptSpecification.numberToRunInParallel);
        threadPools.add(threadPool);
        // kick off the user journey(s), one per thread
        List<UserJourneyThread> userJourneyThreads = new ArrayList<>();
        for (int ujCtr = 0; ujCtr < testScriptSpecification.totalNumberToRun; ujCtr++) {
            ApiClient apiClient = apiClientList.get(ujCtr % apiClientList.size());
            userJourneyThreads.add(new UserJourneyThread(testScript, userJourneyDescription, apiClient));
        }
        // TODO: support different patterns of kicking off user journeys. here they're all queued at
        // once
        List<Future<UserJourneyResult>> userJourneyFutures = threadPool.invokeAll(userJourneyThreads);
        userJourneyFutureLists.add(userJourneyFutures);
    }
    // wait until all threads either finish or time out
    for (int ctr = 0; ctr < scripts.size(); ctr++) {
        TestScriptSpecification testScriptSpecification = config.testScripts.get(ctr);
        ThreadPoolExecutor threadPool = threadPools.get(ctr);
        threadPool.shutdown();
        long totalTerminationTime = testScriptSpecification.expectedTimeForEach * testScriptSpecification.totalNumberToRun;
        boolean terminatedByItself = threadPool.awaitTermination(totalTerminationTime, testScriptSpecification.expectedTimeForEachUnitObj);
        // if the threads didn't finish in the expected time, then send them interrupts
        if (!terminatedByItself) {
            threadPool.shutdownNow();
        }
        if (!threadPool.awaitTermination(secondsToWaitForPoolShutdown, TimeUnit.SECONDS)) {
            System.out.println("Thread pool for test script " + ctr + " (" + testScriptSpecification.name + ") failed to terminate.");
        }
    }
    // compile the results from all thread pools
    for (int ctr = 0; ctr < scripts.size(); ctr++) {
        List<Future<UserJourneyResult>> userJourneyFutureList = userJourneyFutureLists.get(ctr);
        TestScriptSpecification testScriptSpecification = config.testScripts.get(ctr);
        for (Future<UserJourneyResult> userJourneyFuture : userJourneyFutureList) {
            UserJourneyResult result = null;
            if (userJourneyFuture.isDone())
                try {
                    // user journey thread completed and populated its own return object, which may include
                    // an exception
                    result = userJourneyFuture.get();
                    result.completed = true;
                } catch (ExecutionException execEx) {
                    // user journey thread threw an exception and didn't populate its own return object
                    result = new UserJourneyResult(testScriptSpecification.name, "");
                    result.completed = false;
                    result.exceptionThrown = execEx;
                }
            else {
                // user journey either was never started or got cancelled before it finished
                result = new UserJourneyResult(testScriptSpecification.name, "");
                result.completed = false;
            }
            userJourneyResults.add(result);
        }
    }
    // call the cleanup method of each test script
    Exception cleanupExceptionThrown = callTestScriptCleanups();
    if (cleanupExceptionThrown != null) {
        throw new RuntimeException("Error calling test script cleanup methods.", cleanupExceptionThrown);
    }
    // delete the deployment and restore any Kubernetes settings
    if (!config.server.skipDeployment) {
        deleteDeployment();
    }
    if (!config.server.skipKubernetes) {
        restoreKubernetesSettings();
    }
    // cleanup data project
    cleanupLeftoverTestData();
}
Also used : ArrayList(java.util.ArrayList) AccessToken(com.google.auth.oauth2.AccessToken) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials) TestScriptSpecification(runner.config.TestScriptSpecification) TestUserSpecification(runner.config.TestUserSpecification) ExecutionException(java.util.concurrent.ExecutionException) ApiClient(bio.terra.datarepo.client.ApiClient) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) Future(java.util.concurrent.Future) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor)

Example 8 with AccessToken

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

the class GoogleIdTokenAuthTest method testMockUserCredentials.

@Test
public void testMockUserCredentials() throws IOException, GeneralSecurityException, InterruptedException {
    final MockResponse tokenResponse = new MockResponse().setBody(Utils.getDefaultJsonFactory().toString(ImmutableMap.of("id_token", "test-id-token")));
    metadataServer.enqueue(tokenResponse);
    metadataServer.start();
    final AccessToken accessToken = new AccessToken("test-access-token", Date.from(Instant.now().plus(Duration.ofDays(1))));
    final GoogleCredentials credentials = UserCredentials.newBuilder().setTokenServerUri(URI.create("http://localhost:" + metadataServer.getPort() + "/get-test-token")).setAccessToken(accessToken).setRefreshToken("user-refresh-token").setClientId("user-id").setClientSecret("user-secret").build();
    Assume.assumeThat(credentials, is(instanceOf(UserCredentials.class)));
    final GoogleIdTokenAuth idTokenAuth = GoogleIdTokenAuth.of(credentials);
    final Optional<String> token = idTokenAuth.getToken("http://styx.foo.bar");
    assertThat(token, is(Optional.of("test-id-token")));
    final RecordedRequest recordedRequest = metadataServer.takeRequest();
    final Map<String, String> requestBody = Splitter.on('&').withKeyValueSeparator('=').split(recordedRequest.getBody().readUtf8());
    assertThat(requestBody, is(ImmutableMap.of("grant_type", "refresh_token", "refresh_token", "user-refresh-token", "client_id", "user-id", "client_secret", "user-secret")));
    assertThat(recordedRequest.getPath(), is("/get-test-token"));
    assertThat(recordedRequest.getHeader("Authorization"), is("Bearer test-access-token"));
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) AccessToken(com.google.auth.oauth2.AccessToken) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials) Test(org.junit.Test)

Example 9 with AccessToken

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

the class GoogleIdTokenAuth method getServiceAccountIdTokenUsingAccessToken.

private String getServiceAccountIdTokenUsingAccessToken(GoogleCredentials credentials, String targetAudience) throws IOException {
    final Oauth2 oauth2 = new Oauth2.Builder(httpTransport, JSON_FACTORY, null).build();
    final AccessToken accessToken = accessToken(withScopes(credentials, ImmutableList.of("https://www.googleapis.com/auth/userinfo.email")));
    final Tokeninfo info = oauth2.tokeninfo().setAccessToken(accessToken.getTokenValue()).execute();
    final String principal = info.getEmail();
    if (principal == null) {
        throw new IOException("Unable to look up principal email, credentials missing email scope?");
    }
    if (!SERVICE_ACCOUNT_PATTERN.matcher(principal).matches()) {
        throw new IOException("Principal is not a service account, unable to acquire id token: " + principal);
    }
    return getServiceAccountIdTokenUsingAccessToken(credentials, principal, targetAudience);
}
Also used : AccessToken(com.google.auth.oauth2.AccessToken) Oauth2(com.google.api.services.oauth2.Oauth2) IOException(java.io.IOException) Tokeninfo(com.google.api.services.oauth2.model.Tokeninfo)

Example 10 with AccessToken

use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project bqjdbc by looker-open-source.

the class Oauth2Bigquery method authorizeViaToken.

/**
 * Authorizes a bigquery Connection with the given OAuth 2.0 Access Token
 *
 * @param oauthToken
 * @return Authorized Bigquery Connection via OAuth Token
 * @throws SQLException
 */
public static Bigquery authorizeViaToken(String oauthToken, String userAgent, Integer connectTimeout, Integer readTimeout, String rootUrl, HttpTransport httpTransport, List<String> targetServiceAccounts, String projectId) throws SQLException {
    GoogleCredentials credential = GoogleCredentials.create(new AccessToken(oauthToken, null));
    logger.debug("Creating a new bigquery client.");
    Bigquery.Builder bqBuilder = createBqBuilderForCredential(credential, connectTimeout, readTimeout, httpTransport, userAgent, rootUrl, targetServiceAccounts, oauthToken, projectId);
    return new MinifiedBigquery(bqBuilder);
}
Also used : MinifiedBigquery(com.google.api.services.bigquery.MinifiedBigquery) Builder(com.google.api.services.bigquery.Bigquery.Builder) AccessToken(com.google.auth.oauth2.AccessToken) Bigquery(com.google.api.services.bigquery.Bigquery) MinifiedBigquery(com.google.api.services.bigquery.MinifiedBigquery) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials)

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