Java Code Examples for com.google.auth.oauth2.GoogleCredentials#refreshAccessToken()

The following examples show how to use com.google.auth.oauth2.GoogleCredentials#refreshAccessToken() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractInteropTest.java    From grpc-java with Apache License 2.0 9 votes vote down vote up
/** Sends a unary rpc with raw oauth2 access token credentials. */
public void oauth2AuthToken(String jsonKey, InputStream credentialsStream, String authScope)
    throws Exception {
  GoogleCredentials utilCredentials =
      GoogleCredentials.fromStream(credentialsStream);
  utilCredentials = utilCredentials.createScoped(Arrays.asList(authScope));
  AccessToken accessToken = utilCredentials.refreshAccessToken();

  OAuth2Credentials credentials = OAuth2Credentials.create(accessToken);

  TestServiceGrpc.TestServiceBlockingStub stub = blockingStub
      .withCallCredentials(MoreCallCredentials.from(credentials));
  final SimpleRequest request = SimpleRequest.newBuilder()
      .setFillUsername(true)
      .setFillOauthScope(true)
      .build();

  final SimpleResponse response = stub.unaryCall(request);
  assertFalse(response.getUsername().isEmpty());
  assertTrue("Received username: " + response.getUsername(),
      jsonKey.contains(response.getUsername()));
  assertFalse(response.getOauthScope().isEmpty());
  assertTrue("Received oauth scope: " + response.getOauthScope(),
      authScope.contains(response.getOauthScope()));
}
 
Example 2
Source File: AbstractInteropTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/** Sends a unary rpc with raw oauth2 access token credentials. */
public void oauth2AuthToken(String jsonKey, InputStream credentialsStream, String authScope)
    throws Exception {
  GoogleCredentials utilCredentials =
      GoogleCredentials.fromStream(credentialsStream);
  utilCredentials = utilCredentials.createScoped(Arrays.asList(authScope));
  AccessToken accessToken = utilCredentials.refreshAccessToken();

  OAuth2Credentials credentials = OAuth2Credentials.create(accessToken);

  TestServiceGrpc.TestServiceBlockingStub stub = blockingStub
      .withCallCredentials(MoreCallCredentials.from(credentials));
  final SimpleRequest request = SimpleRequest.newBuilder()
      .setFillUsername(true)
      .setFillOauthScope(true)
      .build();

  final SimpleResponse response = stub.unaryCall(request);
  assertFalse(response.getUsername().isEmpty());
  assertTrue("Received username: " + response.getUsername(),
      jsonKey.contains(response.getUsername()));
  assertFalse(response.getOauthScope().isEmpty());
  assertTrue("Received oauth scope: " + response.getOauthScope(),
      authScope.contains(response.getOauthScope()));
}
 
Example 3
Source File: FirebaseAuthIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomTokenWithIAM() throws Exception {
  FirebaseApp masterApp = IntegrationTestUtils.ensureDefaultApp();
  GoogleCredentials credentials = ImplFirebaseTrampolines.getCredentials(masterApp);
  AccessToken token = credentials.getAccessToken();
  if (token == null) {
    token = credentials.refreshAccessToken();
  }
  FirebaseOptions options = new FirebaseOptions.Builder()
      .setCredentials(GoogleCredentials.create(token))
      .setServiceAccountId(((ServiceAccountSigner) credentials).getAccount())
      .setProjectId(IntegrationTestUtils.getProjectId())
      .build();
  FirebaseApp customApp = FirebaseApp.initializeApp(options, "tempApp");
  try {
    FirebaseAuth auth = FirebaseAuth.getInstance(customApp);
    String customToken = auth.createCustomTokenAsync("user1").get();
    String idToken = signInWithCustomToken(customToken);
    FirebaseToken decoded = auth.verifyIdTokenAsync(idToken).get();
    assertEquals("user1", decoded.getUid());
  } finally {
    customApp.delete();
  }
}
 
Example 4
Source File: GoogleAuthClient.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/**
 * The app requires 2 arguments as described in
 * @see <a href="../../../../../../GOOGLE_AUTH_EXAMPLE.md">Google Auth Example README</a>
 *
 * arg0 = location of the JSON file for the service account you created in the GCP console
 * arg1 = project name in the form "projects/balmy-cirrus-225307" where "balmy-cirrus-225307" is
 *        the project ID for the project you created.
 *
 */
public static void main(String[] args) throws Exception {
  if (args.length < 2) {
    logger.severe("Usage: please pass 2 arguments:\n" +
                  "arg0 = location of the JSON file for the service account you created in the GCP console\n" +
                  "arg1 = project name in the form \"projects/xyz\" where \"xyz\" is the project ID of the project you created.\n");
    System.exit(1);
  }
  GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(args[0]));

  // We need to create appropriate scope as per https://cloud.google.com/storage/docs/authentication#oauth-scopes
  credentials = credentials.createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));

  // credentials must be refreshed before the access token is available
  credentials.refreshAccessToken();
  GoogleAuthClient client =
          new GoogleAuthClient("pubsub.googleapis.com", 443, MoreCallCredentials.from(credentials));

  try {
    client.getTopics(args[1]);
  } finally {
    client.shutdown();
  }
}
 
Example 5
Source File: AccessBoundaryUtilsTest.java    From gcp-token-broker with Apache License 2.0 5 votes vote down vote up
/**
 * Check that the access token isn't modified if the target is null.
 */
@Test
public void testTargetNull() throws IOException {
    GoogleCredentials credentials = CloudStorageUtils.getCloudStorageCredentials();
    com.google.auth.oauth2.AccessToken rawAccessToken = credentials.refreshAccessToken();
    AccessToken accessToken = new AccessToken(rawAccessToken.getTokenValue(), rawAccessToken.getExpirationTime().getTime());
    AccessToken boundedToken = AccessBoundaryUtils.addAccessBoundary(accessToken, null);
    assertEquals(boundedToken.getValue(), rawAccessToken.getTokenValue());
    assertEquals(boundedToken.getExpiresAt(), rawAccessToken.getExpirationTime().getTime());
}
 
Example 6
Source File: AccessBoundaryUtilsTest.java    From gcp-token-broker with Apache License 2.0 5 votes vote down vote up
/**
 * Same as testTargetNull but with the empty string value.
 */
@Test
public void testTargetEmptyString() throws IOException {
    GoogleCredentials credentials = CloudStorageUtils.getCloudStorageCredentials();
    com.google.auth.oauth2.AccessToken rawAccessToken = credentials.refreshAccessToken();
    AccessToken accessToken = new AccessToken(rawAccessToken.getTokenValue(), rawAccessToken.getExpirationTime().getTime());
    AccessToken boundedToken = AccessBoundaryUtils.addAccessBoundary(accessToken, "");
    assertEquals(boundedToken.getValue(), rawAccessToken.getTokenValue());
    assertEquals(boundedToken.getExpiresAt(), rawAccessToken.getExpirationTime().getTime());
}
 
Example 7
Source File: AccessBoundaryUtilsTest.java    From gcp-token-broker with Apache License 2.0 5 votes vote down vote up
/**
 * Check that the access token is modified if the target is set to a resource.
 */
@Test
public void testBoundary() throws IOException {
    GoogleCredentials credentials = CloudStorageUtils.getCloudStorageCredentials();
    com.google.auth.oauth2.AccessToken rawAccessToken = credentials.refreshAccessToken();
    AccessToken accessToken = new AccessToken(rawAccessToken.getTokenValue(), rawAccessToken.getExpirationTime().getTime());
    AccessToken boundedToken = AccessBoundaryUtils.addAccessBoundary(accessToken, MOCK_BUCKET);
    assertNotEquals(boundedToken.getValue(), rawAccessToken.getTokenValue());
    assertNotEquals(boundedToken.getExpiresAt(), rawAccessToken.getExpirationTime().getTime());
    // TODO: Verify the token is bounded to the bucket
}
 
Example 8
Source File: SpeechService.java    From black-mirror with MIT License 5 votes vote down vote up
@Override
protected AccessToken doInBackground(Void... voids) {
    final SharedPreferences prefs =
            getSharedPreferences(PREFS, Context.MODE_PRIVATE);
    String tokenValue = prefs.getString(PREF_ACCESS_TOKEN_VALUE, null);
    long expirationTime = prefs.getLong(PREF_ACCESS_TOKEN_EXPIRATION_TIME, -1);

    // Check if the current token is still valid for a while
    if (tokenValue != null && expirationTime > 0) {
        if (expirationTime
                > System.currentTimeMillis() + ACCESS_TOKEN_EXPIRATION_TOLERANCE) {
            return new AccessToken(tokenValue, new Date(expirationTime));
        }
    }

    // ***** WARNING *****
    // In this sample, we load the credential from a JSON file stored in a raw resource
    // folder of this client app. You should never do this in your app. Instead, store
    // the file in your server and obtain an access token from there.
    // *******************
    final InputStream stream = getResources().openRawResource(R.raw.credential);
    try {
        final GoogleCredentials credentials = GoogleCredentials.fromStream(stream)
                .createScoped(SCOPE);
        final AccessToken token = credentials.refreshAccessToken();
        prefs.edit()
                .putString(PREF_ACCESS_TOKEN_VALUE, token.getTokenValue())
                .putLong(PREF_ACCESS_TOKEN_EXPIRATION_TIME,
                        token.getExpirationTime().getTime())
                .apply();
        return token;
    } catch (IOException e) {
        Log.e(TAG, "Failed to obtain access token.", e);
    }
    return null;
}
 
Example 9
Source File: SpeechService.java    From android-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
protected AccessToken doInBackground(Void... voids) {
    final SharedPreferences prefs =
            getSharedPreferences(PREFS, Context.MODE_PRIVATE);
    String tokenValue = prefs.getString(PREF_ACCESS_TOKEN_VALUE, null);
    long expirationTime = prefs.getLong(PREF_ACCESS_TOKEN_EXPIRATION_TIME, -1);

    // Check if the current token is still valid for a while
    if (tokenValue != null && expirationTime > 0) {
        if (expirationTime
                > System.currentTimeMillis() + ACCESS_TOKEN_EXPIRATION_TOLERANCE) {
            return new AccessToken(tokenValue, new Date(expirationTime));
        }
    }

    // ***** WARNING *****
    // In this sample, we load the credential from a JSON file stored in a raw resource
    // folder of this client app. You should never do this in your app. Instead, store
    // the file in your server and obtain an access token from there.
    // *******************
    final InputStream stream = getResources().openRawResource(R.raw.credential);
    try {
        final GoogleCredentials credentials = GoogleCredentials.fromStream(stream)
                .createScoped(SCOPE);
        final AccessToken token = credentials.refreshAccessToken();
        prefs.edit()
                .putString(PREF_ACCESS_TOKEN_VALUE, token.getTokenValue())
                .putLong(PREF_ACCESS_TOKEN_EXPIRATION_TIME,
                        token.getExpirationTime().getTime())
                .apply();
        return token;
    } catch (IOException e) {
        Log.e(TAG, "Failed to obtain access token.", e);
    }
    return null;
}
 
Example 10
Source File: LabelsSample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Add or modify a label on a dataset.
 *
 * See <a href="https://cloud.google.com/bigquery/docs/labeling-datasets">the BigQuery
 * documentation</a>.
 */
public static void labelDataset(
    String projectId, String datasetId, String labelKey, String labelValue) throws IOException {

  // Authenticate requests using Google Application Default credentials.
  GoogleCredentials credential = GoogleCredentials.getApplicationDefault();
  credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/bigquery"));

  // Get a new access token.
  // Note that access tokens have an expiration. You can reuse a token rather than requesting a
  // new one if it is not yet expired.
  AccessToken accessToken = credential.refreshAccessToken();

  // Set the content of the request.
  Dataset dataset = new Dataset();
  dataset.addLabel(labelKey, labelValue);
  HttpContent content = new JsonHttpContent(JSON_FACTORY, dataset);

  // Send the request to the BigQuery API.
  String urlFormat =
      "https://www.googleapis.com/bigquery/v2/projects/%s/datasets/%s"
          + "?fields=labels&access_token=%s";
  GenericUrl url =
      new GenericUrl(String.format(urlFormat, projectId, datasetId, accessToken.getTokenValue()));
  HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
  HttpRequest request = requestFactory.buildPostRequest(url, content);
  request.setParser(JSON_FACTORY.createJsonObjectParser());

  // Workaround for transports which do not support PATCH requests.
  // See: http://stackoverflow.com/a/32503192/101923
  request.setHeaders(new HttpHeaders().set("X-HTTP-Method-Override", "PATCH"));
  HttpResponse response = request.execute();

  // Check for errors.
  if (response.getStatusCode() != 200) {
    throw new RuntimeException(response.getStatusMessage());
  }

  Dataset responseDataset = response.parseAs(Dataset.class);
  System.out.printf(
      "Updated label \"%s\" with value \"%s\"\n",
      labelKey, responseDataset.getLabels().get(labelKey));
}
 
Example 11
Source File: LabelsSample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Add or modify a label on a table.
 *
 * See <a href="https://cloud.google.com/bigquery/docs/labeling-datasets">the BigQuery
 * documentation</a>.
 */
public static void labelTable(
    String projectId, String datasetId, String tableId, String labelKey, String labelValue)
    throws IOException {

  // Authenticate requests using Google Application Default credentials.
  GoogleCredentials credential = GoogleCredentials.getApplicationDefault();
  credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/bigquery"));

  // Get a new access token.
  // Note that access tokens have an expiration. You can reuse a token rather than requesting a
  // new one if it is not yet expired.
  AccessToken accessToken = credential.refreshAccessToken();

  // Set the content of the request.
  Table table = new Table();
  table.addLabel(labelKey, labelValue);
  HttpContent content = new JsonHttpContent(JSON_FACTORY, table);

  // Send the request to the BigQuery API.
  String urlFormat =
      "https://www.googleapis.com/bigquery/v2/projects/%s/datasets/%s/tables/%s"
          + "?fields=labels&access_token=%s";
  GenericUrl url =
      new GenericUrl(
          String.format(urlFormat, projectId, datasetId, tableId, accessToken.getTokenValue()));
  HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
  HttpRequest request = requestFactory.buildPostRequest(url, content);
  request.setParser(JSON_FACTORY.createJsonObjectParser());

  // Workaround for transports which do not support PATCH requests.
  // See: http://stackoverflow.com/a/32503192/101923
  request.setHeaders(new HttpHeaders().set("X-HTTP-Method-Override", "PATCH"));
  HttpResponse response = request.execute();

  // Check for errors.
  if (response.getStatusCode() != 200) {
    throw new RuntimeException(response.getStatusMessage());
  }

  Table responseTable = response.parseAs(Table.class);
  System.out.printf(
      "Updated label \"%s\" with value \"%s\"\n",
      labelKey, responseTable.getLabels().get(labelKey));
}