Search in sources :

Example 91 with AccessToken

use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project terra-cli by DataBiosphere.

the class GoogleOauth method doLoginAndConsent.

/**
 * Do the Google OAuth2 flow for the specified userId. If there is no existing, unexpired
 * credential for this userId, this method will require browser window to ask for consent to
 * access the specified scopes. This browser window is either launched automatically or the URL
 * printed to stdout, depending on the boolean flag.
 *
 * @param scopes list of scopes to request from the user
 * @param clientSecretFile stream to the client secret file
 * @param dataStoreDir directory in which to persist the local credential store
 * @param launchBrowserAutomatically true to launch a browser automatically and listen on a local
 *     server for the token response, false to print the url to stdout and ask the user to
 *     copy/paste the token response to stdin
 * @param loginLandingPage URL of the page to load in the browser upon completion of login
 * @return credentials object for the user
 */
public static UserCredentials doLoginAndConsent(List<String> scopes, InputStream clientSecretFile, File dataStoreDir, boolean launchBrowserAutomatically, String loginLandingPage) throws IOException, GeneralSecurityException {
    // load client_secret.json file
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(clientSecretFile, StandardCharsets.UTF_8));
    // setup the Google OAuth2 flow
    GoogleAuthorizationCodeFlow flow = getOAuth2Flow(scopes, clientSecrets, dataStoreDir);
    // exchange an authorization code for a refresh token
    Credential credential;
    if (launchBrowserAutomatically) {
        // launch a browser window on this machine and listen on a local port for the token response
        LocalServerReceiver receiver = new LocalServerReceiver.Builder().setLandingPages(loginLandingPage, loginLandingPage).build();
        credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize(CREDENTIAL_STORE_KEY);
    } else {
        // print the url to stdout and ask the user to copy/paste the token response to stdin
        credential = new AuthorizationCodeInstalledApp(flow, new StdinReceiver(), new NoLaunchBrowser()).authorize(CREDENTIAL_STORE_KEY);
    }
    // OAuth2 Credentials representing a user's identity and consent
    UserCredentials credentials = UserCredentials.newBuilder().setClientId(clientSecrets.getDetails().getClientId()).setClientSecret(clientSecrets.getDetails().getClientSecret()).setRefreshToken(credential.getRefreshToken()).setAccessToken(new AccessToken(credential.getAccessToken(), new Date(credential.getExpirationTimeMilliseconds()))).build();
    // only try to refresh if the refresh token is set
    if (credentials.getRefreshToken() == null || credentials.getRefreshToken().isEmpty()) {
        logger.info("Refresh token is not set. This is expected when testing, not during normal operation.");
    } else {
        credentials.refresh();
    }
    return credentials;
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) StoredCredential(com.google.api.client.auth.oauth2.StoredCredential) InputStreamReader(java.io.InputStreamReader) AccessToken(com.google.auth.oauth2.AccessToken) GoogleAuthorizationCodeFlow(com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow) AuthorizationCodeInstalledApp(com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp) GoogleClientSecrets(com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets) UserCredentials(com.google.auth.oauth2.UserCredentials) LocalServerReceiver(com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver) Date(java.util.Date)

Example 92 with AccessToken

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

the class KubernetesClientUtils method buildKubernetesClientObject.

private static CoreV1Api buildKubernetesClientObject(String clusterName, String region, String project) throws Exception {
    // call the fetchGKECrednetials script that uses gcloud to generate the kubeconfig file
    List<String> scriptArgs = new ArrayList<>();
    scriptArgs.add("tools/fetchGKECredentials.sh");
    scriptArgs.add(clusterName);
    scriptArgs.add(region);
    scriptArgs.add(project);
    executeCommand("sh", scriptArgs);
    // path to kubeconfig file, that was just created/updated by gcloud get-credentials above
    String kubeConfigPath = System.getProperty("user.home") + "/.kube/config";
    // load the kubeconfig object from the file
    InputStreamReader filereader = new InputStreamReader(new FileInputStream(kubeConfigPath), Charset.forName("UTF-8"));
    KubeConfig kubeConfig = KubeConfig.loadKubeConfig(filereader);
    // get a refreshed SA access token and its expiration time
    AccessToken accessToken = getApplicationDefaultAccessToken();
    Instant tokenExpiration = accessToken.getExpirationTime().toInstant();
    String expiryUTC = tokenExpiration.atZone(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT);
    // USERS: build list of one user, the SA
    LinkedHashMap<String, Object> authConfigSA = new LinkedHashMap<>();
    authConfigSA.put("access-token", accessToken.getTokenValue());
    authConfigSA.put("expiry", expiryUTC);
    LinkedHashMap<String, Object> authProviderSA = new LinkedHashMap<>();
    authProviderSA.put("name", "gcp");
    authProviderSA.put("config", authConfigSA);
    LinkedHashMap<String, Object> userSA = new LinkedHashMap<>();
    userSA.put("auth-provider", authProviderSA);
    LinkedHashMap<String, Object> userWrapperSA = new LinkedHashMap<>();
    userWrapperSA.put("name", clusterName);
    userWrapperSA.put("user", userSA);
    ArrayList<Object> usersList = new ArrayList<>();
    usersList.add(userWrapperSA);
    // CONTEXTS: build list of one context, the specified cluster
    LinkedHashMap<String, Object> context = new LinkedHashMap<>();
    context.put("cluster", clusterName);
    // when is the user ever different from the cluster name?
    context.put("user", clusterName);
    LinkedHashMap<String, Object> contextWrapper = new LinkedHashMap<>();
    contextWrapper.put("name", clusterName);
    contextWrapper.put("context", context);
    ArrayList<Object> contextsList = new ArrayList<>();
    contextsList.add(contextWrapper);
    // CLUSTERS: use the cluster list read in from the kubeconfig file, because I can't figure out how to get the
    // certificate-authority-data and server address for the cluster via the Java client library, only with gcloud
    ArrayList<Object> clusters = kubeConfig.getClusters();
    // build the config object, replacing the contexts and users lists from the kubeconfig file with the ones
    // constructed programmatically above
    kubeConfig = new KubeConfig(contextsList, clusters, usersList);
    kubeConfig.setContext(clusterName);
    // build the client object from the config
    ApiClient client = ClientBuilder.kubeconfig(kubeConfig).build();
    // set the global default client to the one created above because the CoreV1Api constructor gets the client
    // object from the global configuration
    Configuration.setDefaultApiClient(client);
    return new CoreV1Api();
}
Also used : InputStreamReader(java.io.InputStreamReader) Instant(java.time.Instant) ArrayList(java.util.ArrayList) ApiClient(io.kubernetes.client.openapi.ApiClient) FileInputStream(java.io.FileInputStream) LinkedHashMap(java.util.LinkedHashMap) AccessToken(com.google.auth.oauth2.AccessToken) KubeConfig(io.kubernetes.client.util.KubeConfig) CoreV1Api(io.kubernetes.client.openapi.apis.CoreV1Api)

Example 93 with AccessToken

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

the class DataRepoFixtures method getStorage.

public Storage getStorage(String token) {
    GoogleCredentials googleCredentials = GoogleCredentials.create(new AccessToken(token, null));
    StorageOptions storageOptions = StorageOptions.newBuilder().setCredentials(googleCredentials).build();
    return storageOptions.getService();
}
Also used : StorageOptions(com.google.cloud.storage.StorageOptions) AccessToken(com.google.auth.oauth2.AccessToken) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials)

Example 94 with AccessToken

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

the class OAuthClientServerTest method testRequestSigningWithExceedingCache.

/**
 * Tests configuration of the nonce cache on the server side.
 */
@Test
public void testRequestSigningWithExceedingCache() {
    final Feature filterFeature = OAuth1ClientSupport.builder(new ConsumerCredentials(CONSUMER_KEY, SECRET_CONSUMER_KEY)).feature().accessToken(new AccessToken(PROMETHEUS_TOKEN, PROMETHEUS_SECRET)).build();
    final Client client = ClientBuilder.newBuilder().register(filterFeature).build();
    final URI resourceUri = UriBuilder.fromUri(getBaseUri()).path("resource").build();
    final WebTarget target = client.target(resourceUri);
    Response response;
    for (int i = 0; i < 20; i++) {
        System.out.println("request: " + i);
        response = target.request().get();
        assertEquals(200, response.getStatus());
        assertEquals("prometheus", response.readEntity(String.class));
        i++;
        response = target.path("admin").request().get();
        assertEquals(200, response.getStatus());
        assertEquals(true, response.readEntity(boolean.class));
    }
    // now the nonce cache is full
    response = target.request().get();
    assertEquals(401, response.getStatus());
}
Also used : Response(javax.ws.rs.core.Response) ConsumerCredentials(org.glassfish.jersey.client.oauth1.ConsumerCredentials) AccessToken(org.glassfish.jersey.client.oauth1.AccessToken) WebTarget(javax.ws.rs.client.WebTarget) Client(javax.ws.rs.client.Client) Feature(javax.ws.rs.core.Feature) OAuth1ServerFeature(org.glassfish.jersey.server.oauth1.OAuth1ServerFeature) LoggingFeature(org.glassfish.jersey.logging.LoggingFeature) URI(java.net.URI) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Example 95 with AccessToken

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

the class OauthClientAuthorizationFlowTest method testOAuthClientFeature.

/**
 * Tests mainly the client functionality. The test client registers
 * {@link org.glassfish.jersey.client.oauth1.OAuth1ClientFilter} and uses the filter only to sign requests. So, it does not
 * use the filter to perform authorization flow. However, each request that this test performs is actually a request used
 * during the authorization flow.
 * <p/>
 * The server side of this test extracts header authorization values and tests that signatures are
 * correct for each request type.
 */
@Test
public void testOAuthClientFeature() {
    final URI baseUri = getBaseUri();
    // baseline for requests
    final OAuth1Builder oAuth1Builder = OAuth1ClientSupport.builder(new ConsumerCredentials("dpf43f3p2l4k3l03", "kd94hf93k423kf44")).timestamp("1191242090").nonce("hsu94j3884jdopsl").signatureMethod(PlaintextMethod.NAME).version("1.0");
    final Feature feature = oAuth1Builder.feature().build();
    final Client client = client();
    client.register(LoggingFeature.class);
    final WebTarget target = client.target(baseUri);
    // simulate request for Request Token (temporary credentials)
    String responseEntity = target.path("request_token").register(feature).request().post(Entity.entity("entity", MediaType.TEXT_PLAIN_TYPE), String.class);
    assertEquals(responseEntity, "oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03");
    final Feature feature2 = oAuth1Builder.timestamp("1191242092").nonce("dji430splmx33448").feature().accessToken(new AccessToken("hh5s93j4hdidpola", "hdhd0244k9j7ao03")).build();
    // simulate request for Access Token
    responseEntity = target.path("access_token").register(feature2).request().post(Entity.entity("entity", MediaType.TEXT_PLAIN_TYPE), String.class);
    assertEquals(responseEntity, "oauth_token=nnch734d00sl2jdk&oauth_token_secret=pfkkdhi9sl3r4s00");
    final Feature feature3 = oAuth1Builder.nonce("kllo9940pd9333jh").signatureMethod("HMAC-SHA1").timestamp("1191242096").feature().accessToken(new AccessToken("nnch734d00sl2jdk", "pfkkdhi9sl3r4s00")).build();
    // based on Access Token
    responseEntity = target.path("/photos").register(feature3).queryParam("file", "vacation.jpg").queryParam("size", "original").request().get(String.class);
    assertEquals(responseEntity, "PHOTO");
}
Also used : ConsumerCredentials(org.glassfish.jersey.client.oauth1.ConsumerCredentials) AccessToken(org.glassfish.jersey.client.oauth1.AccessToken) OAuth1Builder(org.glassfish.jersey.client.oauth1.OAuth1Builder) WebTarget(javax.ws.rs.client.WebTarget) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Client(javax.ws.rs.client.Client) URI(java.net.URI) Feature(javax.ws.rs.core.Feature) OAuth1SignatureFeature(org.glassfish.jersey.oauth1.signature.OAuth1SignatureFeature) LoggingFeature(org.glassfish.jersey.logging.LoggingFeature) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

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