GithubHelp home page GithubHelp logo

googleapis / google-auth-library-java Goto Github PK

View Code? Open in Web Editor NEW
403.0 73.0 216.0 3.96 MB

Open source Auth client library for Java

Home Page: https://developers.google.com/identity

License: BSD 3-Clause "New" or "Revised" License

Java 98.22% Shell 1.65% Batchfile 0.05% Python 0.08%

google-auth-library-java's Introduction

Google Auth Library

Open source authentication client library for Java.

stable Maven

This project consists of 3 artifacts:

Table of contents:

Quickstart

If you are using Maven, add this to your pom.xml file (notice that you can replace google-auth-library-oauth2-http with any of google-auth-library-credentials and google-auth-library-appengine, depending on your application needs):

<dependency>
  <groupId>com.google.auth</groupId>
  <artifactId>google-auth-library-oauth2-http</artifactId>
  <version>1.19.0</version>
</dependency>

If you are using Gradle, add this to your dependencies

implementation 'com.google.auth:google-auth-library-oauth2-http:1.19.0'

If you are using SBT, add this to your dependencies

libraryDependencies += "com.google.auth" % "google-auth-library-oauth2-http" % "1.19.0"

google-auth-library-oauth2-http

Application Default Credentials

This library provides an implementation of Application Default Credentials for Java. Application Default Credentials provide a simple way to get authorization credentials for use in calling Google APIs.

They are best suited for cases when the call needs to have the same identity and authorization level for the application independent of the user. This is the recommended approach to authorize calls to Cloud APIs, particularly when you're building an application that uses Google Cloud Platform.

Application Default Credentials also support workload identity federation to access Google Cloud resources from non-Google Cloud platforms including Amazon Web Services (AWS), Microsoft Azure or any identity provider that supports OpenID Connect (OIDC). Workload identity federation is recommended for non-Google Cloud environments as it avoids the need to download, manage and store service account private keys locally, see: Workload Identity Federation.

Getting Application Default Credentials

To get Application Default Credentials use GoogleCredentials.getApplicationDefault() or GoogleCredentials.getApplicationDefault(HttpTransportFactory). These methods return the Application Default Credentials which are used to identify and authorize the whole application. The following are searched (in order) to find the Application Default Credentials:

  1. Credentials file pointed to by the GOOGLE_APPLICATION_CREDENTIALS environment variable
  2. Credentials provided by the Google Cloud SDK gcloud auth application-default login command
  3. Google App Engine built-in credentials
  4. Google Cloud Shell built-in credentials
  5. Google Compute Engine built-in credentials
    • Skip this check by setting the environment variable NO_GCE_CHECK=true
    • Customize the GCE metadata server address by setting the environment variable GCE_METADATA_HOST=<hostname>

Explicit Credential Loading

To get Credentials from a Service Account JSON key use GoogleCredentials.fromStream(InputStream) or GoogleCredentials.fromStream(InputStream, HttpTransportFactory). Note that the credentials must be refreshed before the access token is available.

GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream("/path/to/credentials.json"));
credentials.refreshIfExpired();
AccessToken token = credentials.getAccessToken();
// OR
AccessToken token = credentials.refreshAccessToken();

ImpersonatedCredentials

Allows a credentials issued to a user or service account to impersonate another. The source project using ImpersonatedCredentials must enable the "IAMCredentials" API. Also, the target service account must grant the orginating principal the "Service Account Token Creator" IAM role.

String credPath = "/path/to/svc_account.json";
ServiceAccountCredentials sourceCredentials = ServiceAccountCredentials
     .fromStream(new FileInputStream(credPath));
sourceCredentials = (ServiceAccountCredentials) sourceCredentials
    .createScoped(Arrays.asList("https://www.googleapis.com/auth/iam"));

ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create(sourceCredentials,
    "[email protected]", null,
    Arrays.asList("https://www.googleapis.com/auth/devstorage.read_only"), 300);

Storage storage_service = StorageOptions.newBuilder().setProjectId("project-id")
    .setCredentials(targetCredentials).build().getService();

for (Bucket b : storage_service.list().iterateAll())
    System.out.println(b); 

Workload Identity Federation

Using workload identity federation, your application can access Google Cloud resources from Amazon Web Services (AWS), Microsoft Azure, or any identity provider that supports OpenID Connect (OIDC).

Traditionally, applications running outside Google Cloud have used service account keys to access Google Cloud resources. Using identity federation, your workload can impersonate a service account. This lets the external workload access Google Cloud resources directly, eliminating the maintenance and security burden associated with service account keys.

Accessing resources from AWS

In order to access Google Cloud resources from Amazon Web Services (AWS), the following requirements are needed:

  • A workload identity pool needs to be created.
  • AWS needs to be added as an identity provider in the workload identity pool (the Google organization policy needs to allow federation from AWS).
  • Permission to impersonate a service account needs to be granted to the external identity.

Follow the detailed instructions on how to configure workload identity federation from AWS.

After configuring the AWS provider to impersonate a service account, a credential configuration file needs to be generated. Unlike service account credential files, the generated credential configuration file contains non-sensitive metadata to instruct the library on how to retrieve external subject tokens and exchange them for service account access tokens. The configuration file can be generated by using the gcloud CLI.

To generate the AWS workload identity configuration, run the following command:

# Generate an AWS configuration file.
gcloud iam workload-identity-pools create-cred-config \
    projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$AWS_PROVIDER_ID \
    --service-account $SERVICE_ACCOUNT_EMAIL \
    --aws \
    --output-file /path/to/generated/config.json

Where the following variables need to be substituted:

  • $PROJECT_NUMBER: The Google Cloud project number.
  • $POOL_ID: The workload identity pool ID.
  • $AWS_PROVIDER_ID: The AWS provider ID.
  • $SERVICE_ACCOUNT_EMAIL: The email of the service account to impersonate.

This generates the configuration file in the specified output file.

If you are using AWS IMDSv2, an additional flag --enable-imdsv2 needs to be added to the gcloud iam workload-identity-pools create-cred-config command:

gcloud iam workload-identity-pools create-cred-config \
    projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$AWS_PROVIDER_ID \
    --service-account $SERVICE_ACCOUNT_EMAIL \
    --aws \
    --output-file /path/to/generated/config.json \
    --enable-imdsv2

You can now use the Auth library to call Google Cloud resources from AWS.

Access resources from Microsoft Azure

In order to access Google Cloud resources from Microsoft Azure, the following requirements are needed:

  • A workload identity pool needs to be created.
  • Azure needs to be added as an identity provider in the workload identity pool (the Google organization policy needs to allow federation from Azure).
  • The Azure tenant needs to be configured for identity federation.
  • Permission to impersonate a service account needs to be granted to the external identity.

Follow the detailed instructions on how to configure workload identity federation from Microsoft Azure.

After configuring the Azure provider to impersonate a service account, a credential configuration file needs to be generated. Unlike service account credential files, the generated credential configuration file contains non-sensitive metadata to instruct the library on how to retrieve external subject tokens and exchange them for service account access tokens. The configuration file can be generated by using the gcloud CLI.

To generate the Azure workload identity configuration, run the following command:

# Generate an Azure configuration file.
gcloud iam workload-identity-pools create-cred-config \
    projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$AZURE_PROVIDER_ID \
    --service-account $SERVICE_ACCOUNT_EMAIL \
    --azure \
    --output-file /path/to/generated/config.json

Where the following variables need to be substituted:

  • $PROJECT_NUMBER: The Google Cloud project number.
  • $POOL_ID: The workload identity pool ID.
  • $AZURE_PROVIDER_ID: The Azure provider ID.
  • $SERVICE_ACCOUNT_EMAIL: The email of the service account to impersonate.

This generates the configuration file in the specified output file.

You can now use the Auth library to call Google Cloud resources from Azure.

Accessing resources from an OIDC identity provider

In order to access Google Cloud resources from an identity provider that supports OpenID Connect (OIDC), the following requirements are needed:

  • A workload identity pool needs to be created.
  • An OIDC identity provider needs to be added in the workload identity pool (the Google organization policy needs to allow federation from the identity provider).
  • Permission to impersonate a service account needs to be granted to the external identity.

Follow the detailed instructions on how to configure workload identity federation from an OIDC identity provider.

After configuring the OIDC provider to impersonate a service account, a credential configuration file needs to be generated. Unlike service account credential files, the generated credential configuration file contains non-sensitive metadata to instruct the library on how to retrieve external subject tokens and exchange them for service account access tokens. The configuration file can be generated by using the gcloud CLI.

For OIDC providers, the Auth library can retrieve OIDC tokens either from a local file location (file-sourced credentials) or from a local server (URL-sourced credentials).

File-sourced credentials For file-sourced credentials, a background process needs to be continuously refreshing the file location with a new OIDC token prior to expiration. For tokens with one hour lifetimes, the token needs to be updated in the file every hour. The token can be stored directly as plain text or in JSON format.

To generate a file-sourced OIDC configuration, run the following command:

# Generate an OIDC configuration file for file-sourced credentials.
gcloud iam workload-identity-pools create-cred-config \
    projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$OIDC_PROVIDER_ID \
    --service-account $SERVICE_ACCOUNT_EMAIL \
    --credential-source-file $PATH_TO_OIDC_ID_TOKEN \
    # Optional arguments for file types. Default is "text":
    # --credential-source-type "json" \
    # Optional argument for the field that contains the OIDC credential.
    # This is required for json.
    # --credential-source-field-name "id_token" \
    --output-file /path/to/generated/config.json

Where the following variables need to be substituted:

  • $PROJECT_NUMBER: The Google Cloud project number.
  • $POOL_ID: The workload identity pool ID.
  • $OIDC_PROVIDER_ID: The OIDC provider ID.
  • $SERVICE_ACCOUNT_EMAIL: The email of the service account to impersonate.
  • $PATH_TO_OIDC_ID_TOKEN: The file path used to retrieve the OIDC token.

This generates the configuration file in the specified output file.

URL-sourced credentials For URL-sourced credentials, a local server needs to host a GET endpoint to return the OIDC token. The response can be in plain text or JSON. Additional required request headers can also be specified.

To generate a URL-sourced OIDC workload identity configuration, run the following command:

# Generate an OIDC configuration file for URL-sourced credentials.
gcloud iam workload-identity-pools create-cred-config \
    projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$OIDC_PROVIDER_ID \
    --service-account $SERVICE_ACCOUNT_EMAIL \
    --credential-source-url $URL_TO_GET_OIDC_TOKEN \
    --credential-source-headers $HEADER_KEY=$HEADER_VALUE \
    # Optional arguments for file types. Default is "text":
    # --credential-source-type "json" \
    # Optional argument for the field that contains the OIDC credential.
    # This is required for json.
    # --credential-source-field-name "id_token" \
    --output-file /path/to/generated/config.json

Where the following variables need to be substituted:

  • $PROJECT_NUMBER: The Google Cloud project number.
  • $POOL_ID: The workload identity pool ID.
  • $OIDC_PROVIDER_ID: The OIDC provider ID.
  • $SERVICE_ACCOUNT_EMAIL: The email of the service account to impersonate.
  • $URL_TO_GET_OIDC_TOKEN: The URL of the local server endpoint to call to retrieve the OIDC token.
  • $HEADER_KEY and $HEADER_VALUE: The additional header key/value pairs to pass along the GET request to $URL_TO_GET_OIDC_TOKEN, e.g. Metadata-Flavor=Google.

You can now use the Auth library to call Google Cloud resources from an OIDC provider.

Using Executable-sourced credentials with OIDC and SAML

Executable-sourced credentials For executable-sourced credentials, a local executable is used to retrieve the 3rd party token. The executable must handle providing a valid, unexpired OIDC ID token or SAML assertion in JSON format to stdout.

To use executable-sourced credentials, the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable must be set to 1.

To generate an executable-sourced workload identity configuration, run the following command:

# Generate a configuration file for executable-sourced credentials.
gcloud iam workload-identity-pools create-cred-config \
    projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$PROVIDER_ID \
    --service-account=$SERVICE_ACCOUNT_EMAIL \
    --subject-token-type=$SUBJECT_TOKEN_TYPE \
    # The absolute path for the program, including arguments.
    # e.g. --executable-command="/path/to/command --foo=bar"
    --executable-command=$EXECUTABLE_COMMAND \
    # Optional argument for the executable timeout. Defaults to 30s.
    # --executable-timeout-millis=$EXECUTABLE_TIMEOUT \
    # Optional argument for the absolute path to the executable output file.
    # See below on how this argument impacts the library behaviour.
    # --executable-output-file=$EXECUTABLE_OUTPUT_FILE \
    --output-file /path/to/generated/config.json

Where the following variables need to be substituted:

  • $PROJECT_NUMBER: The Google Cloud project number.
  • $POOL_ID: The workload identity pool ID.
  • $PROVIDER_ID: The OIDC or SAML provider ID.
  • $SERVICE_ACCOUNT_EMAIL: The email of the service account to impersonate.
  • $SUBJECT_TOKEN_TYPE: The subject token type.
  • $EXECUTABLE_COMMAND: The full command to run, including arguments. Must be an absolute path to the program.

The --executable-timeout-millis flag is optional. This is the duration for which the auth library will wait for the executable to finish, in milliseconds. Defaults to 30 seconds when not provided. The maximum allowed value is 2 minutes. The minimum is 5 seconds.

The --executable-output-file flag is optional. If provided, the file path must point to the 3PI credential response generated by the executable. This is useful for caching the credentials. By specifying this path, the Auth libraries will first check for its existence before running the executable. By caching the executable JSON response to this file, it improves performance as it avoids the need to run the executable until the cached credentials in the output file are expired. The executable must handle writing to this file - the auth libraries will only attempt to read from this location. The format of contents in the file should match the JSON format expected by the executable shown below.

To retrieve the 3rd party token, the library will call the executable using the command specified. The executable's output must adhere to the response format specified below. It must output the response to stdout.

A sample successful executable OIDC response:

{
  "version": 1,
  "success": true,
  "token_type": "urn:ietf:params:oauth:token-type:id_token",
  "id_token": "HEADER.PAYLOAD.SIGNATURE",
  "expiration_time": 1620499962
}

A sample successful executable SAML response:

{
  "version": 1,
  "success": true,
  "token_type": "urn:ietf:params:oauth:token-type:saml2",
  "saml_response": "...",
  "expiration_time": 1620499962
}

A sample executable error response:

{
  "version": 1,
  "success": false,
  "code": "401",
  "message": "Caller not authorized."
}

These are all required fields for an error response. The code and message fields will be used by the library as part of the thrown exception.

For successful responses, the expiration_time field is only required when an output file is specified in the credential configuration.

Response format fields summary:

  • version: The version of the JSON output. Currently only version 1 is supported.
  • success: When true, the response must contain the 3rd party token and token type. The response must also contain the expiration_time field if an output file was specified in the credential configuration. The executable must also exit with exit code 0. When false, the response must contain the error code and message fields and exit with a non-zero value.
  • token_type: The 3rd party subject token type. Must be urn:ietf:params:oauth:token-type:jwt, urn:ietf:params:oauth:token-type:id_token, or urn:ietf:params:oauth:token-type:saml2.
  • id_token: The 3rd party OIDC token.
  • saml_response: The 3rd party SAML response.
  • expiration_time: The 3rd party subject token expiration time in seconds (unix epoch time).
  • code: The error code string.
  • message: The error message.

All response types must include both the version and success fields.

  • Successful responses must include the token_type and one of id_token or saml_response. The expiration_time field must also be present if an output file was specified in the credential configuration.
  • Error responses must include both the code and message fields.

The library will populate the following environment variables when the executable is run:

  • GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE: The audience field from the credential configuration. Always present.
  • GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE: This expected subject token type. Always present.
  • GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL: The service account email. Only present when service account impersonation is used.
  • GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE: The output file location from the credential configuration. Only present when specified in the credential configuration.

These environment variables can be used by the executable to avoid hard-coding these values.

Security considerations

The following security practices are highly recommended:

  • Access to the script should be restricted as it will be displaying credentials to stdout. This ensures that rogue processes do not gain access to the script.
  • The configuration file should not be modifiable. Write access should be restricted to avoid processes modifying the executable command portion.

Given the complexity of using executable-sourced credentials, it is recommended to use the existing supported mechanisms (file-sourced/URL-sourced) for providing 3rd party credentials unless they do not meet your specific requirements.

You can now use the Auth library to call Google Cloud resources from an OIDC or SAML provider.

Using a custom supplier with OIDC and SAML

A custom implementation of IdentityPoolSubjectTokenSupplier can be used while building IdentityPoolCredentials to supply a subject token which can be exchanged for a GCP access token. The supplier must return a valid, unexpired subject token when called by the GCP credential.

IdentityPoolCredentials do not cache the returned token, so caching logic should be implemented in the token supplier to prevent multiple requests for the same subject token.

import java.io.IOException;

public class CustomTokenSupplier implements IdentityPoolSubjectTokenSupplier {

  @Override
  public String getSubjectToken(ExternalAccountSupplierContext context) throws IOException {
    // Any call to the supplier will pass a context object with the requested
    // audience and subject token type.
    string audience = context.getAudience();
    string tokenType = context.getSubjectTokenType();

    try {
      // Return a valid, unexpired token for the requested audience and token type.
      // Note that IdentityPoolCredentials do not cache the subject token so
      // any caching logic needs to be implemented in the token supplier.
      return retrieveToken(audience, tokenType);
    } catch (Exception e) {
      // If token is unavailable, throw IOException.
      throw new IOException(e);
    }
  }

  private String retrieveToken(string tokenType, string audience) {
    // Retrieve a subject token of the requested type for the requested audience.
  }
}
CustomTokenSupplier tokenSupplier = new CustomTokenSupplier();
IdentityPoolCredentials identityPoolCredentials =
    IdentityPoolCredentials.newBuilder()
        .setSubjectTokenSupplier(tokenSupplier) // Sets the token supplier.
        .setAudience(...) // Sets the GCP audience.
        .setSubjectTokenType(SubjectTokenTypes.JWT) // Sets the subject token type.
        .build();

Where the audience is: //iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$WORKLOAD_POOL_ID/providers/$PROVIDER_ID

Where the following variables need to be substituted:

  • $PROJECT_NUMBER: The Google Cloud project number.
  • $WORKLOAD_POOL_ID: The workload identity pool ID.
  • $PROVIDER_ID: The provider ID.

The values for audience, service account impersonation URL, and any other builder field can also be found by generating a credential configuration file with the gcloud CLI.

Using a custom supplier with AWS

A custom implementation of AwsSecurityCredentialsSupplier can be provided when initializing AwsCredentials. If provided, the AwsCredentials instance will defer to the supplier to retrieve AWS security credentials to exchange for a GCP access token. The supplier must return valid, unexpired AWS security credentials when called by the GCP credential.

AwsCredentials do not cache the returned AWS security credentials or region, so caching logic should be implemented in the supplier to prevent multiple requests for the same resources.

class CustomAwsSupplier implements AwsSecurityCredentialsSupplier {
  @Override
  AwsSecurityCredentials getAwsSecurityCredentials(ExternalAccountSupplierContext context) throws IOException {
    // Any call to the supplier will pass a context object with the requested
    // audience.
    string audience = context.getAudience();

    try {
      // Return valid, unexpired AWS security credentials for the requested audience.
      // Note that AwsCredentials do not cache the AWS security credentials so
      // any caching logic needs to be implemented in the credentials' supplier.
      return retrieveAwsSecurityCredentials(audience);
    } catch (Exception e) {
      // If credentials are unavailable, throw IOException.
      throw new IOException(e);
    }
  }

  @Override
  String getRegion(ExternalAccountSupplierContext context) throws IOException {
    try {
      // Return a valid AWS region. i.e. "us-east-2".
      // Note that AwsCredentials do not cache the region so
      // any caching logic needs to be implemented in the credentials' supplier.
      return retrieveAwsRegion();
    } catch (Exception e) {
      // If region is unavailable, throw IOException.
      throw new IOException(e);
    }
  }

  private AwsSecurityCredentials retrieveAwsSecurityCredentials(string audience) {
    // Retrieve Aws security credentials for the requested audience.
  }

  private String retrieveAwsRegion() {
    // Retrieve current AWS region.
  }
}
CustomAwsSupplier awsSupplier = new CustomAwsSupplier();
AwsCredentials credentials = AwsCredentials.newBuilder()
    .setSubjectTokenType(SubjectTokenTypes.AWS4) // Sets the subject token type.
    .setAudience(...) // Sets the GCP audience.
    .setAwsSecurityCredentialsSupplier(supplier) // Sets the supplier.
    .build();

Where the audience is: //iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$WORKLOAD_POOL_ID/providers/$PROVIDER_ID

Where the following variables need to be substituted:

  • $PROJECT_NUMBER: The Google Cloud project number.
  • $WORKLOAD_POOL_ID: The workload identity pool ID.
  • $PROVIDER_ID: The provider ID.

The values for audience, service account impersonation URL, and any other builder field can also be found by generating a credential configuration file with the gcloud CLI.

Configurable Token Lifetime

When creating a credential configuration with workload identity federation using service account impersonation, you can provide an optional argument to configure the service account access token lifetime.

To generate the configuration with configurable token lifetime, run the following command (this example uses an AWS configuration, but the token lifetime can be configured for all workload identity federation providers):

# Generate an AWS configuration file with configurable token lifetime.
gcloud iam workload-identity-pools create-cred-config \
    projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$AWS_PROVIDER_ID \
    --service-account $SERVICE_ACCOUNT_EMAIL \
    --aws \
    --output-file /path/to/generated/config.json \
    --service-account-token-lifetime-seconds $TOKEN_LIFETIME

Where the following variables need to be substituted:

  • $PROJECT_NUMBER: The Google Cloud project number.
  • $POOL_ID: The workload identity pool ID.
  • $AWS_PROVIDER_ID: The AWS provider ID.
  • $SERVICE_ACCOUNT_EMAIL: The email of the service account to impersonate.
  • $TOKEN_LIFETIME: The desired lifetime duration of the service account access token in seconds.

The service-account-token-lifetime-seconds flag is optional. If not provided, this defaults to one hour. The minimum allowed value is 600 (10 minutes) and the maximum allowed value is 43200 (12 hours). If a lifetime greater than one hour is required, the service account must be added as an allowed value in an Organization Policy that enforces the constraints/iam.allowServiceAccountCredentialLifetimeExtension constraint.

Note that configuring a short lifetime (e.g. 10 minutes) will result in the library initiating the entire token exchange flow every 10 minutes, which will call the 3rd party token provider even if the 3rd party token is not expired.

Workforce Identity Federation

Workforce identity federation lets you use an external identity provider (IdP) to authenticate and authorize a workforceโ€”a group of users, such as employees, partners, and contractorsโ€”using IAM, so that the users can access Google Cloud services. Workforce identity federation extends Google Cloud's identity capabilities to support syncless, attribute-based single sign on.

With workforce identity federation, your workforce can access Google Cloud resources using an external identity provider (IdP) that supports OpenID Connect (OIDC) or SAML 2.0 such as Azure Active Directory (Azure AD), Active Directory Federation Services (AD FS), Okta, and others.

Accessing resources using an OIDC or SAML 2.0 identity provider

In order to access Google Cloud resources from an identity provider that supports OpenID Connect (OIDC), the following requirements are needed:

  • A workforce identity pool needs to be created.
  • An OIDC or SAML 2.0 identity provider needs to be added in the workforce pool.

Follow the detailed instructions on how to configure workforce identity federation.

After configuring an OIDC or SAML 2.0 provider, a credential configuration file needs to be generated. The generated credential configuration file contains non-sensitive metadata to instruct the library on how to retrieve external subject tokens and exchange them for GCP access tokens. The configuration file can be generated by using the gcloud CLI.

The Auth library can retrieve external subject tokens from a local file location (file-sourced credentials), from a local server (URL-sourced credentials) or by calling an executable (executable-sourced credentials).

File-sourced credentials For file-sourced credentials, a background process needs to be continuously refreshing the file location with a new subject token prior to expiration. For tokens with one hour lifetimes, the token needs to be updated in the file every hour. The token can be stored directly as plain text or in JSON format.

To generate a file-sourced OIDC configuration, run the following command:

# Generate an OIDC configuration file for file-sourced credentials.
gcloud iam workforce-pools create-cred-config \
    locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \
    --subject-token-type=urn:ietf:params:oauth:token-type:id_token \
    --credential-source-file=$PATH_TO_OIDC_ID_TOKEN \
    --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \
    # Optional arguments for file types. Default is "text":
    # --credential-source-type "json" \
    # Optional argument for the field that contains the OIDC credential.
    # This is required for json.
    # --credential-source-field-name "id_token" \
    --output-file=/path/to/generated/config.json

Where the following variables need to be substituted:

  • $WORKFORCE_POOL_ID: The workforce pool ID.
  • $PROVIDER_ID: The provider ID.
  • $PATH_TO_OIDC_ID_TOKEN: The file path used to retrieve the OIDC token.
  • $WORKFORCE_POOL_USER_PROJECT: The project number associated with the workforce pools user project.

To generate a file-sourced SAML configuration, run the following command:

# Generate a SAML configuration file for file-sourced credentials.
gcloud iam workforce-pools create-cred-config \
    locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \
    --credential-source-file=$PATH_TO_SAML_ASSERTION \
    --subject-token-type=urn:ietf:params:oauth:token-type:saml2 \
    --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \
    --output-file=/path/to/generated/config.json 

Where the following variables need to be substituted:

  • $WORKFORCE_POOL_ID: The workforce pool ID.
  • $PROVIDER_ID: The provider ID.
  • $PATH_TO_SAML_ASSERTION: The file path used to retrieve the base64-encoded SAML assertion.
  • $WORKFORCE_POOL_USER_PROJECT: The project number associated with the workforce pools user project.

These commands generate the configuration file in the specified output file.

URL-sourced credentials For URL-sourced credentials, a local server needs to host a GET endpoint to return the OIDC token. The response can be in plain text or JSON. Additional required request headers can also be specified.

To generate a URL-sourced OIDC workforce identity configuration, run the following command:

# Generate an OIDC configuration file for URL-sourced credentials.
gcloud iam workforce-pools create-cred-config \
    locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \
    --subject-token-type=urn:ietf:params:oauth:token-type:id_token \
    --credential-source-url=$URL_TO_RETURN_OIDC_ID_TOKEN \
    --credential-source-headers $HEADER_KEY=$HEADER_VALUE \
    --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \
    --output-file=/path/to/generated/config.json

Where the following variables need to be substituted:

  • $WORKFORCE_POOL_ID: The workforce pool ID.
  • $PROVIDER_ID: The provider ID.
  • $URL_TO_RETURN_OIDC_ID_TOKEN: The URL of the local server endpoint.
  • $HEADER_KEY and $HEADER_VALUE: The additional header key/value pairs to pass along the GET request to $URL_TO_GET_OIDC_TOKEN, e.g. Metadata-Flavor=Google.
  • $WORKFORCE_POOL_USER_PROJECT: The project number associated with the workforce pools user project.

To generate a URL-sourced SAML configuration, run the following command:

# Generate a SAML configuration file for file-sourced credentials.
gcloud iam workforce-pools create-cred-config \
    locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \
    --subject-token-type=urn:ietf:params:oauth:token-type:saml2 \
    --credential-source-url=$URL_TO_GET_SAML_ASSERTION \
    --credential-source-headers $HEADER_KEY=$HEADER_VALUE \
    --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \
    --output-file=/path/to/generated/config.json 

These commands generate the configuration file in the specified output file.

Where the following variables need to be substituted:

  • $WORKFORCE_POOL_ID: The workforce pool ID.
  • $PROVIDER_ID: The provider ID.
  • $URL_TO_GET_SAML_ASSERTION: The URL of the local server endpoint.
  • $HEADER_KEY and $HEADER_VALUE: The additional header key/value pairs to pass along the GET request to $URL_TO_GET_SAML_ASSERTION, e.g. Metadata-Flavor=Google.
  • $WORKFORCE_POOL_USER_PROJECT: The project number associated with the workforce pools user project.

Using external account authorized user workforce credentials

External account authorized user credentials allow you to sign in with a web browser to an external identity provider account via the gcloud CLI and create a configuration for the auth library to use.

To generate an external account authorized user workforce identity configuration, run the following command:

gcloud auth application-default login --login-config=$LOGIN_CONFIG

Where the following variable needs to be substituted:

This will open a browser flow for you to sign in via the configured third party identity provider and then will store the external account authorized user configuration at the well known ADC location. The auth library will then use the provided refresh token from the configuration to generate and refresh an access token to call Google Cloud services.

Note that the default lifetime of the refresh token is one hour, after which a new configuration will need to be generated from the gcloud CLI. The lifetime can be modified by changing the session duration of the workforce pool, and can be set as high as 12 hours.

Using Executable-sourced workforce credentials with OIDC and SAML

Executable-sourced credentials For executable-sourced credentials, a local executable is used to retrieve the 3rd party token. The executable must handle providing a valid, unexpired OIDC ID token or SAML assertion in JSON format to stdout.

To use executable-sourced credentials, the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable must be set to 1.

To generate an executable-sourced workforce identity configuration, run the following command:

# Generate a configuration file for executable-sourced credentials.
gcloud iam workforce-pools create-cred-config \
    locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \
    --subject-token-type=$SUBJECT_TOKEN_TYPE \
    # The absolute path for the program, including arguments.
    # e.g. --executable-command="/path/to/command --foo=bar"
    --executable-command=$EXECUTABLE_COMMAND \
    # Optional argument for the executable timeout. Defaults to 30s.
    # --executable-timeout-millis=$EXECUTABLE_TIMEOUT \
    # Optional argument for the absolute path to the executable output file.
    # See below on how this argument impacts the library behaviour.
    # --executable-output-file=$EXECUTABLE_OUTPUT_FILE \
    --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \
    --output-file /path/to/generated/config.json

Where the following variables need to be substituted:

  • $WORKFORCE_POOL_ID: The workforce pool ID.
  • $PROVIDER_ID: The provider ID.
  • $SUBJECT_TOKEN_TYPE: The subject token type.
  • $EXECUTABLE_COMMAND: The full command to run, including arguments. Must be an absolute path to the program.
  • $WORKFORCE_POOL_USER_PROJECT: The project number associated with the workforce pools user project.

The --executable-timeout-millis flag is optional. This is the duration for which the auth library will wait for the executable to finish, in milliseconds. Defaults to 30 seconds when not provided. The maximum allowed value is 2 minutes. The minimum is 5 seconds.

The --executable-output-file flag is optional. If provided, the file path must point to the 3rd party credential response generated by the executable. This is useful for caching the credentials. By specifying this path, the Auth libraries will first check for its existence before running the executable. By caching the executable JSON response to this file, it improves performance as it avoids the need to run the executable until the cached credentials in the output file are expired. The executable must handle writing to this file - the auth libraries will only attempt to read from this location. The format of contents in the file should match the JSON format expected by the executable shown below.

To retrieve the 3rd party token, the library will call the executable using the command specified. The executable's output must adhere to the response format specified below. It must output the response to stdout.

Refer to the using executable-sourced credentials with Workload Identity Federation above for the executable response specification.

Using a custom supplier for workforce credentials with OIDC and SAML

A custom implementation of IdentityPoolSubjectTokenSupplier can be used while building IdentityPoolCredentials to supply a subject token which can be exchanged for a GCP access token. The supplier must return a valid, unexpired subject token when called by the GCP credential.

IdentityPoolCredentials do not cache the returned token, so caching logic should be implemented in the token supplier to prevent multiple requests for the same subject token.

import java.io.IOException;

public class CustomTokenSupplier implements IdentityPoolSubjectTokenSupplier {

  @Override
  public String getSubjectToken(ExternalAccountSupplierContext context) throws IOException {
    // Any call to supplier will pass a context object with the requested
    // audience and subject token type.
    string audience = context.getAudience();
    string tokenType = context.getSubjectTokenType();

    try {
      // Return a valid, unexpired token for the requested audience and token type.
      // Note that the IdentityPoolCredential does not cache the subject token so
      // any caching logic needs to be implemented in the token supplier.
      return retrieveToken(audience, tokenType);
    } catch (Exception e) {
      // If token is unavailable, throw IOException.
      throw new IOException(e);
    }
  }

  private String retrieveToken(string tokenType, string audience) {
    // Retrieve a subject token of the requested type for the requested audience.
  }
}
CustomTokenSupplier tokenSupplier = new CustomTokenSupplier();
IdentityPoolCredentials identityPoolCredentials =
    IdentityPoolCredentials.newBuilder()
        .setSubjectTokenSupplier(tokenSupplier) // Sets the token supplier.
        .setAudience(...) // Sets the GCP audience.
        .setSubjectTokenType(SubjectTokenTypes.JWT) // Sets the subject token type.
        .setWorkforcePoolUserProject(...) // Sets the workforce pool user project.
        .build();

Where the audience is: //iam.googleapis.com/locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID

Where the following variables need to be substituted:

  • $WORKFORCE_POOL_ID: The workforce pool ID.
  • $PROVIDER_ID: The provider ID.

and the workforce pool user project is the project number associated with the workforce pools user project.

The values for audience, service account impersonation URL, and any other builder field can also be found by generating a credential configuration file with the gcloud CLI.

Security considerations

The following security practices are highly recommended:

  • Access to the script should be restricted as it will be displaying credentials to stdout. This ensures that rogue processes do not gain access to the script.
  • The configuration file should not be modifiable. Write access should be restricted to avoid processes modifying the executable command portion.

Given the complexity of using executable-sourced credentials, it is recommended to use the existing supported mechanisms (file-sourced/URL-sourced) for providing 3rd party credentials unless they do not meet your specific requirements.

You can now use the Auth library to call Google Cloud resources from an OIDC or SAML provider.

Using External Identities

External identities can be used with Application Default Credentials. In order to use external identities with Application Default Credentials, you need to generate the JSON credentials configuration file for your external identity as described above. Once generated, store the path to this file in theGOOGLE_APPLICATION_CREDENTIALS environment variable.

export GOOGLE_APPLICATION_CREDENTIALS=/path/to/config.json

The library can now choose the right type of client and initialize credentials from the context provided in the configuration file.

GoogleCredentials googleCredentials = GoogleCredentials.getApplicationDefault();

String projectId = "your-project-id";
String url = "https://storage.googleapis.com/storage/v1/b?project=" + projectId;

HttpCredentialsAdapter credentialsAdapter = new HttpCredentialsAdapter(googleCredentials);
HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory(credentialsAdapter);
HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(url));

JsonObjectParser parser = new JsonObjectParser(GsonFactory.getDefaultInstance());
request.setParser(parser);

HttpResponse response = request.execute();
System.out.println(response.parseAsString());

You can also explicitly initialize external account clients using the generated configuration file.

ExternalAccountCredentials credentials = 
    ExternalAccountCredentials.fromStream(new FileInputStream("/path/to/credentials.json"));
Security Considerations

Note that this library does not perform any validation on the token_url, token_info_url, or service_account_impersonation_url fields of the credential configuration. It is not recommended to use a credential configuration that you did not generate with the gcloud CLI unless you verify that the URL fields point to a googleapis.com domain.

Downscoping with Credential Access Boundaries

Downscoping with Credential Access Boundaries enables the ability to downscope, or restrict, the Identity and Access Management (IAM) permissions that a short-lived credential can use for Cloud Storage.

The DownscopedCredentials class can be used to produce a downscoped access token from a CredentialAccessBoundary and a source credential. The Credential Access Boundary specifies which resources the newly created credential can access, as well as an upper bound on the permissions that are available on each resource. Using downscoped credentials ensures tokens in flight always have the least privileges (Principle of Least Privilege).

The snippet below shows how to initialize a CredentialAccessBoundary with one AccessBoundaryRule which specifies that the downscoped token will have readonly access to objects starting with "customer-a" in bucket "bucket-123":

// Create the AccessBoundaryRule.
String availableResource = "//storage.googleapis.com/projects/_/buckets/bucket-123";
String availablePermission = "inRole:roles/storage.objectViewer";
String expression =  "resource.name.startsWith('projects/_/buckets/bucket-123/objects/customer-a')";

CredentialAccessBoundary.AccessBoundaryRule rule =
    CredentialAccessBoundary.AccessBoundaryRule.newBuilder()
        .setAvailableResource(availableResource)
        .addAvailablePermission(availablePermission)
        .setAvailabilityCondition(
        CredentialAccessBoundary.AccessBoundaryRule.AvailabilityCondition.newBuilder().setExpression(expression).build())
        .build();

// Create the CredentialAccessBoundary with the rule.
CredentialAccessBoundary credentialAccessBoundary = 
        CredentialAccessBoundary.newBuilder().addRule(rule).build();

The common pattern of usage is to have a token broker with elevated access generate these downscoped credentials from higher access source credentials and pass the downscoped short-lived access tokens to a token consumer via some secure authenticated channel for limited access to Google Cloud Storage resources.

Using the CredentialAccessBoundary created above in the Token Broker:

// Retrieve the source credentials from ADC.
GoogleCredentials sourceCredentials = GoogleCredentials.getApplicationDefault()
        .createScoped("https://www.googleapis.com/auth/cloud-platform");

// Initialize the DownscopedCredentials class.
DownscopedCredentials downscopedCredentials =
    DownscopedCredentials.newBuilder()
        .setSourceCredential(credentials)
        .setCredentialAccessBoundary(credentialAccessBoundary)
        .build();

// Retrieve the downscoped access token.
// This will need to be passed to the Token Consumer.
AccessToken downscopedAccessToken = downscopedCredentials.refreshAccessToken();

A token broker can be set up on a server in a private network. Various workloads (token consumers) in the same network will send authenticated requests to that broker for downscoped tokens to access or modify specific google cloud storage buckets.

The broker will instantiate downscoped credentials instances that can be used to generate short lived downscoped access tokens which will be passed to the token consumer.

Putting it all together:

// Retrieve the source credentials from ADC.
GoogleCredentials sourceCredentials = GoogleCredentials.getApplicationDefault()
        .createScoped("https://www.googleapis.com/auth/cloud-platform");

// Create an Access Boundary Rule which will restrict the downscoped token to having readonly
// access to objects starting with "customer-a" in bucket "bucket-123".
String availableResource = "//storage.googleapis.com/projects/_/buckets/bucket-123";
String availablePermission = "inRole:roles/storage.objectViewer";
String expression =  "resource.name.startsWith('projects/_/buckets/bucket-123/objects/customer-a')";
        
CredentialAccessBoundary.AccessBoundaryRule rule =
    CredentialAccessBoundary.AccessBoundaryRule.newBuilder()
        .setAvailableResource(availableResource)
        .addAvailablePermission(availablePermission)
        .setAvailabilityCondition(
            new AvailabilityCondition(expression, /* title= */ null, /* description= */ null))
        .build();

// Initialize the DownscopedCredentials class.
DownscopedCredentials downscopedCredentials =
    DownscopedCredentials.newBuilder()
        .setSourceCredential(credentials)
        .setCredentialAccessBoundary(CredentialAccessBoundary.newBuilder().addRule(rule).build())
        .build();

// Retrieve the downscoped access token.
// This will need to be passed to the Token Consumer.
AccessToken downscopedAccessToken = downscopedCredentials.refreshAccessToken();

These downscoped access tokens can be used by the Token Consumer via OAuth2Credentials or OAuth2CredentialsWithRefresh. This credential can then be used to initialize a storage client instance to access Google Cloud Storage resources with restricted access.

// You can pass an `OAuth2RefreshHandler` to `OAuth2CredentialsWithRefresh` which will allow the
// library to seamlessly handle downscoped token refreshes on expiration.
OAuth2CredentialsWithRefresh.OAuth2RefreshHandler handler = 
        new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() {
    @Override
    public AccessToken refreshAccessToken() {
      // Add the logic here that retrieves the token from your Token Broker.
      return accessToken;
    }
};

// Downscoped token retrieved from token broker.
AccessToken downscopedToken = handler.refreshAccessToken();

// Build the OAuth2CredentialsWithRefresh from the downscoped token and pass a refresh handler 
// to handle token expiration. Passing the original downscoped token or the expiry here is optional,
// as the refresh_handler will generate the downscoped token on demand.
OAuth2CredentialsWithRefresh credentials =
    OAuth2CredentialsWithRefresh.newBuilder()
        .setAccessToken(downscopedToken)
        .setRefreshHandler(handler)
        .build();

// Use the credentials with the Cloud Storage SDK.
StorageOptions options = StorageOptions.newBuilder().setCredentials(credentials).build();
Storage storage = options.getService();

// Call GCS APIs.
// Since we passed the downscoped credential, we will have have limited readonly access to objects
// starting with "customer-a" in bucket "bucket-123".
storage.get(...)

Note: Only Cloud Storage supports Credential Access Boundaries. Other Google Cloud services do not support this feature.

Configuring a Proxy

For HTTP clients, a basic proxy can be configured by using http.proxyHost and related system properties as documented by Java Networking and Proxies.

For a more custom proxy (e.g. for an authenticated proxy), provide a custom HttpTransportFactory to GoogleCredentials:

import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.apache.v2.ApacheHttpTransport;
import com.google.auth.http.HttpTransportFactory;
import com.google.auth.oauth2.GoogleCredentials;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.ProxyAuthenticationStrategy;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;

import java.io.IOException;

public class ProxyExample {
  public GoogleCredentials getCredentials() throws IOException {
    HttpTransportFactory httpTransportFactory = getHttpTransportFactory(
        "some-host", 8080, "some-username", "some-password"
    );

    return GoogleCredentials.getApplicationDefault(httpTransportFactory);
  }

  public HttpTransportFactory getHttpTransportFactory(String proxyHost, int proxyPort, String proxyUsername, String proxyPassword) {
    HttpHost proxyHostDetails = new HttpHost(proxyHost, proxyPort);
    HttpRoutePlanner httpRoutePlanner = new DefaultProxyRoutePlanner(proxyHostDetails);

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(
        new AuthScope(proxyHostDetails.getHostName(), proxyHostDetails.getPort()),
        new UsernamePasswordCredentials(proxyUsername, proxyPassword)
    );

    HttpClient httpClient = ApacheHttpTransport.newDefaultHttpClientBuilder()
        .setRoutePlanner(httpRoutePlanner)
        .setProxyAuthenticationStrategy(ProxyAuthenticationStrategy.INSTANCE)
        .setDefaultCredentialsProvider(credentialsProvider)
        .build();

    final HttpTransport httpTransport = new ApacheHttpTransport(httpClient);
    return new HttpTransportFactory() {
      @Override
      public HttpTransport create() {
        return httpTransport;
      }
    };
  }
}

The above example requires com.google.http-client:google-http-client-apache-v2.

Using Credentials with google-http-client

Credentials provided by com.google.auth:google-auth-library-oauth2-http can be used with Google's HTTP-based clients. We provide a HttpCredentialsAdapter which can be used as an HttpRequestInitializer, the last argument for their builders.

import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.services.bigquery.Bigquery;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;

GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);

Bigquery bq = new Bigquery.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
    .setApplicationName(APPLICATION_NAME)
    .build();

Verifying JWT Tokens (Beta)

To verify a JWT token, use the TokenVerifier class.

Verifying a Signature

To verify a signature, use the default TokenVerifier:

import com.google.api.client.json.webtoken.JsonWebSignature;
import com.google.auth.oauth2.TokenVerifier;

TokenVerifier tokenVerifier = TokenVerifier.newBuilder().build();
try {
  JsonWebSignature jsonWebSignature = tokenVerifier.verify(tokenString);
  // optionally verify additional claims
  if (!"expected-value".equals(jsonWebSignature.getPayload().get("additional-claim"))) {
    // handle custom verification error
  }
} catch (TokenVerifier.VerificationException e) {
  // invalid token
}

Customizing the TokenVerifier

To customize a TokenVerifier, instantiate it via its builder:

import com.google.api.client.json.webtoken.JsonWebSignature;
import com.google.auth.oauth2.TokenVerifier;

TokenVerifier tokenVerifier = TokenVerifier.newBuilder()
  .setAudience("audience-to-verify")
  .setIssuer("issuer-to-verify")
  .build();
try {
  JsonWebSignature jsonWebSignature = tokenVerifier.verify(tokenString);
  // optionally verify additional claims
  if (!"expected-value".equals(jsonWebSignature.getPayload().get("additional-claim"))) {
    // handle custom verification error
  }
} catch (TokenVerifier.VerificationException e) {
  // invalid token
}

For more options, see the TokenVerifier.Builder documentation.

google-auth-library-credentials

This artifact contains base classes and interfaces for Google credentials:

  • Credentials: base class for an authorized identity. Implementations of this class can be used to authorize your application
  • RequestMetadataCallback: interface for the callback that receives the result of the asynchronous Credentials.getRequestMetadata(URI, Executor, RequestMetadataCallback)
  • ServiceAccountSigner: interface for a service account signer. Implementations of this class are capable of signing byte arrays using the credentials associated to a Google Service Account

google-auth-library-appengine

This artifact depends on the App Engine SDK (appengine-api-1.0-sdk) and should be used only by applications running on App Engine environments that use urlfetch. The AppEngineCredentials class allows you to authorize your App Engine application given an instance of AppIdentityService.

Usage:

import com.google.appengine.api.appidentity.AppIdentityService;
import com.google.appengine.api.appidentity.AppIdentityServiceFactory;
import com.google.auth.Credentials;
import com.google.auth.appengine.AppEngineCredentials;

AppIdentityService appIdentityService = AppIdentityServiceFactory.getAppIdentityService();

Credentials credentials =
    AppEngineCredentials.newBuilder()
        .setScopes(...)
        .setAppIdentityService(appIdentityService)
        .build();

Important: com.google.auth.appengine.AppEngineCredentials is a separate class from com.google.auth.oauth2.AppEngineCredentials.

CI Status

Java Version Status
Java 8 Kokoro CI
Java 8 OSX Kokoro CI
Java 8 Windows Kokoro CI
Java 11 Kokoro CI

Contributing

Contributions to this library are always welcome and highly encouraged.

See CONTRIBUTING documentation for more information on how to get started.

Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms. See Code of Conduct for more information.

Running the Tests

To run the tests you will need:

  • Maven 3+
$ mvn test

License

BSD 3-Clause - See LICENSE for more information.

google-auth-library-java's People

Contributors

aeitzman avatar alicejli avatar anthmgoogle avatar arithmetic1728 avatar bigtailwolf avatar captain1653 avatar chingor13 avatar clundin25 avatar dependabot[bot] avatar eaball35 avatar elharo avatar garrettjonesgoogle avatar gcf-owl-bot[bot] avatar igorbernstein2 avatar jeanbza avatar lesv avatar lsirac avatar mpeddada1 avatar mziccard avatar neenu1995 avatar pongad avatar release-please[bot] avatar renovate-bot avatar sai-sunder-s avatar shinfan avatar tcoffee-google avatar timursadykov avatar vchudnov-g avatar yoshi-automation avatar zhangkun83 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

google-auth-library-java's Issues

Add Google App Engine Service Account Support

Add support for the GAE built-in service account, aka. App Identity. Also, add support to Application Default Credentials for detecting this environment and automatically using this identity.

FR: Need a good way to inject secrets besides `gcloud` & `GOOGLE_APPLICATION_CREDENTIALS`

PR's #94 & #144 both want to find a way to improve ADC for non-google cloud providers.

The ADC algorithm is defined to:

  1. Look at environment variable GOOGLE_APPLICATION_CREDENTIALS
  2. Look for gcloud auth application-default login
  3. Get a service account from the GCP Metadata server (GAE & GCP are a bit different, but it's the same idea)

We should see if there is a way to safely and securely inject a secret like a service account JSON into a container running on another cloud platform. (item 3 above).

@jonparrott said: environment variables should not be used to hold secrets.

This is a very important item for us. We are trying get to the point where docker containers can run anywhere, on GCP, on a competing cloud provider, in their own datacenter, or locally in their laptop with just a change in the configuration.

Check CLOUDSDK_CONFIG for default credentials location

In DefaultCredentialsProvider.getWellKnownCredentialsFile(), the environment variable CLOUDSDK_CONFIG isn't checked. Instead, it assumes that the .config directory is in home. If the CLOUDSDK_CONFIG environment variable is set, that should be used instead of home. This would be consistent with the issue reported in the python equivalent of this library (see this issue).

As a result of not checking CLOUDSDK_CONFIG, users can see the issues like this if they install Cloud SDK in a non-default location.

Errors when using Application Default Credentials from within App Engine

When using Application Default Credentials from App Engine, both on the local development server (after logging in via gcloud auth login) and in production, I get the following error message:
java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.

Based on that website, it seems like the behavior should be that the SDK credentials are used in the local development server and the App Engine credentials should be provided without setting the GOOGLE_APPLICATION_CREDENTIALS environment variable.

FR: Expose Project ID from ServiceAccountCredentials

Currently the com.google.auth.oauth2.ServiceAccountCredentials class does not handle the project_id field available in Google service account JSON files. It would be useful if the credential can read this field, and expose it via a new getProjectId() method.

Usecase: We want to use this library within some Firebase SDKs, and we (in some situations) need to know the project ID along with the credential.

HttpCredentialsAdapter should enable refresh and retry for expired or invalid access token

The current HttpCredentialsAdapter will refresh the token if it detects that it has expired on the client side. However, the token can be invalided or expire earlier than this due to clock differences. The adaptere should also detect this case, refresh the token and retry the request.

As a reference, the equivalent credential class in the V1 library does this:
https://github.com/google/google-oauth-java-client/blob/dev/google-oauth-client/src/main/java/com/google/api/client/auth/oauth2/Credential.java

It will require the HttpCredentialsAdapter to implement the HttpUnsuccessfulResponseHandler interface.

Errors when using Application Default Credentials

Exception in thread "main" java.io.IOException: The Application Default Credentials are not available. They are available if running on Google App Engine, Google Compute Engine, or Google Cloud Shell. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
	at com.google.api.client.googleapis.auth.oauth2.DefaultCredentialProvider.getDefaultCredential(DefaultCredentialProvider.java:98)
	at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.getApplicationDefault(GoogleCredential.java:213)
	at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.getApplicationDefault(GoogleCredential.java:191)
	at com.google.cloud.vision.samples.label.LabelApp.getVisionService(LabelApp.java:100)
	at com.google.cloud.vision.samples.label.LabelApp.main(LabelApp.java:73)

BUILD FAILURE

GCE metadata server credentials cannot sign storage blob

With GAE java 8 standard runtime, GCE metadata server is used to retrieve credentials. However, unlike google.appengine.api.app_identity.sign_blob(), metadata sever is not able to sign GCS blob (discussion captured here and here). It seems the timeline for metadata server to enable signing is not clear. This currently blocks java storage client library to run on GAE java 8 standard (googleapis/google-cloud-java#2629). Auth lib should implement IAM signer to provide workaround (as python auth lib did: googleapis/google-auth-library-python#108)

Making Credentials classes Serializable

In order for us to expose google-auth-library-java classes in google-cloud-java (thus dropping our AuthCredentials classes), we need Credentials classes to be Serializable.

One of the main obstacles to making Credentials classes serializable is that some of them contain an HttpTransport field, which is not serializable (see ComputeEngineCredentials for instance).

We faced this issue with our HttpServiceOptions classes and introduced the HttpTransportFactory interface:

  /**
   * A base interface for all {@link HttpTransport} factories.
   *
   * <p>Implementation must provide a public no-arg constructor. Loading of a factory implementation
   * is done via {@link java.util.ServiceLoader}.
   */
  public interface HttpTransportFactory {
    HttpTransport create();
  }

When serializing an option object we only transmit the class name for the transport factory and try to instantiate the factory from its classname upon deserialization.

Do you think something like this could be done for Credentials classes as well? Opinions are welcome.

/cc @anthmgoogle @garrettjonesgoogle @lesv

Can we add a method to OAuth2Credentials that checks if token is almost expired and refreshes if so?

OAuth2Credentials has methods refresh(). But there's no method to check if the token is close to expiring and refresh if so. I want to do these few lines, but these methods are private.

My use case is that I have a long-lived GoogleCredentials instance. I only want to refresh when I need to to minimize unnecessary overhead in making requests to the backend. There are the methods getRequestMetadata() which will essentially do the check and refresh logic, but this method name and parameter is an awkward fit.

Can we expose a new public method in this class that does this?

public void refreshIfExpired() throws IOException {
  synchronized(lock) {
    if (shouldRefresh()) {
      refresh();
    }
  }
}

Bump google-auth-library-java to 1.0.0 (GA)

  • Mark anything @BetaApi or @Internal that we want the flexibility to change later (requires adding a dependency on api-common) - only things unused in google-cloud-java and grpc-auth can be marked this way
  • Remove Guava from the surface
  • Add back any features removed since 0.4.0 (to maintain compatibility with grpc-auth)
  • Any other GA cleanup
  • drop guava-jdk5 support
  • Full end-to-end testing (#293)

Audience URI?

Hi,
I am trying to check whether a google big query table exists.
I instantiated Credentials object as follows:

Credentials c = new ServiceAccountJwtAccessCredentials(
                "client ID",
                "client email",
                privateKey,
                "private key id");
        BigQueryOptions bqo = BigQueryOptions
                .newBuilder()
                .setCredentials(c)
                .setProjectId("project ID")
                .build();
        BigQuery bq = bqo.getService();
        TableId id = TableId.of("dataset name", "table name");
        Table t = bq.getTable(id);
        System.out.println("table exists()? : " + t.exists());

I am getting the following exception:

Exception in thread "main" com.google.cloud.bigquery.BigQueryException: JwtAccess requires Audience uri to be passed in or the defaultAudience to be specified
	at com.google.cloud.bigquery.spi.v2.HttpBigQueryRpc.translate(HttpBigQueryRpc.java:86)
	at com.google.cloud.bigquery.spi.v2.HttpBigQueryRpc.getTable(HttpBigQueryRpc.java:227)
	at com.google.cloud.bigquery.BigQueryImpl$11.call(BigQueryImpl.java:378)
	at com.google.cloud.bigquery.BigQueryImpl$11.call(BigQueryImpl.java:375)
	at com.google.api.gax.retrying.DirectRetryingExecutor.submit(DirectRetryingExecutor.java:94)
	at com.google.cloud.RetryHelper.runWithRetries(RetryHelper.java:54)
	at com.google.cloud.bigquery.BigQueryImpl.getTable(BigQueryImpl.java:375)
	at com.syed.googlecloudstorage.InstantiateStorage.doSecondJob(InstantiateStorage.java:147)
	at com.syed.googlecloudstorage.InstantiateStorage.main(InstantiateStorage.java:131)
Caused by: java.io.IOException: JwtAccess requires Audience uri to be passed in or the defaultAudience to be specified
	at com.google.auth.oauth2.ServiceAccountJwtAccessCredentials.getRequestMetadata(ServiceAccountJwtAccessCredentials.java:257)
	at com.google.auth.http.HttpCredentialsAdapter.initialize(HttpCredentialsAdapter.java:96)
	at com.google.cloud.http.HttpTransportOptions$1.initialize(HttpTransportOptions.java:157)
	at com.google.api.client.http.HttpRequestFactory.buildRequest(HttpRequestFactory.java:93)
	at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.buildHttpRequest(AbstractGoogleClientRequest.java:300)
	at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
	at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
	at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
	at com.google.cloud.bigquery.spi.v2.HttpBigQueryRpc.getTable(HttpBigQueryRpc.java:225)
	... 7 more

Any clues? Can somebody help me on what possible values I can supply for audience uri? Any steps to know that? Please.

Jwt Access Credentials should cache JWTs

The JWT Access Credentials should temporarily cache JWTs. Suggested algorithm:

  • Hash JWTs using Audience as key.
  • Also store the timestamp of last use with each JWT.
  • On access clear any JWT unused for more than 1 hour.

Possible Integer Overflow When Parsing expires_in Values

While running some tests using the MockTokenServerTransport of the Google API client, I noticed that sometimes GoogleCredentials.getExpirationTime() incorrectly returns timestamps that are several days old. This is what's going on:

  1. MockTokenServerTransport has a bug where it reports the expires_in field in milliseconds (3600000), where it should be seconds. I reported this in their Github repo (googleapis/google-api-java-client#1061).
  2. The code in ServiceAccountCredentials class will encounter an integer overflow, when the backend server reports a large expires_in value:

https://github.com/google/google-auth-library-java/blob/master/oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java#L375

    long expiresAtMilliseconds = clock.currentTimeMillis() + expiresInSeconds * 1000;

If expiresInSeconds is large (say 3600000), this code will overflow, and the resulting timestamp will be in the past.

Java is missing ability to do OAuth2 domain wide delegation

This is needed for google-auth-library-java and googleapis/google-api-java-client#1037 (creating an issue for both projects):

User's current way:

GoogleCredential googleCredential = new GoogleCredential.Builder()
     .setTransport(TRANSPORT).setJsonFactory(JSON_FACTORY)
     .setServiceAccountId(emailAddress)
     .setServiceAccountPrivateKeyFromP12File(p12File)
     .setServiceAccountScopes(scopes)
     .setServiceAccountUser(user).build();

Would like: to do:

GoogleCredential googleCredential = 
    GoogleCredential.fromStream(jsonInputStream, TRANSPORT, JSON_FACTORY).createScoped(Collections.singleton(Oauth2Scopes.USERINFO_EMAIL))

Python you just do:

credentials = credentials.create_delegated(user)

HttpCredentialsAdapter should refresh credentials if access token invalid

An access token can become invalid separately from its expiration time due a clock mismatch or other scenarios. If a request fails because the access token is invalid, the adapter should call refresh() to discard the token and retry the request a single time. See google-api-java-client for a reference implementation.

Using guava instead of guava-jdk5 dependency

We now depend on guava-jdk5:13.0. In both google-cloud-java and gax-java we instead depend on standard guava (version 19 and 18 respectively).

Is there any reason for depending on guava-jdk5? If not excluded (as we do in google-cloud-java), this just results in a bunch of duplicated classes in all projects that use standard guava. /cc @anthmgoogle @garrettjonesgoogle

Cannot perform asynchronous refresh of access tokens prior to expiration.

The interface of OAuth2Credentials does not allow an external class to know the expiration time of the currently cached access token. This prevents implementation of asynchronous refresh patterns.

Currently callers must use

credentials.getRequestMetadata()

which will block if the token has expired. This is not ideal for high-performance clients.

auto-refreshing isn't work

Hello all.

I routed here from google-doublecliek-ad-exchange-buyer-api group for OAuth auto-refresh issue. https://groups.google.com/forum/#!topic/google-doubleclick-ad-exchange-buyer-api/ptf3-LO-2Jc

I saw "GoogleCredential takes care of automatically "refreshing" the token" state from below page.
https://developers.google.com/api-client-library/java/google-api-java-client/oauth2

I wrote below but it doesn't refresh token automatically.

String token = ...;
TokenResponse tokenResponse = JacksonFactory.getDefaultInstance().fromString(token, TokenResponse.getClass());
tokenResponse.setRefreshToken("CCCCC");

Credential credential = new GoogleCredential.Builder().setJsonFactory(JacksonFactory.getDefaultInstance())
.setTransport(GoogleNetHttpTransport.newTrustedTransport())
.setClientSecrets("XXXX", "XXXX")
.build().setFromTokenResponse(tokenResponse);
AdExchangeBuyerII buyer = new AdExchangeBuyerII.Builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance(), credential).setApplicationName("").build();

Originally, I set refreshToken at GoogleCredential, but I change it to set it on TokenResponse after Mark's suggestion. But both of them isn't work.

I also add CredentialRefreshListener() to check whether refresh request is sent, but I can't see anyting.

Could you let me know whether my code need to be updated or it is a bug on auth library?

OAuth2 over proxy doesn't work.

I'm using spanner java client with gcloud SDK and trying to connect to Google Spanner from machine that uses proxy for internet access.
I have configured gcloud to use my proxy server and it is ok.
I have specified environment variable GRPC_PROXY_EXP and Spanner requests to spanner.googleapis.com go through proxy and it's ok as well.

But spanner sql requests fail with com.google.cloud.spanner.SpannerException: UNAUTHENTICATED exception because of another error related to OAuth2:

Caused by: java.net.UnknownHostException: accounts.google.com
	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
	at java.net.Socket.connect(Socket.java:589)
	at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:668)
	at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
	at sun.net.www.http.HttpClient.openServer(HttpClient.java:432)
	at sun.net.www.http.HttpClient.openServer(HttpClient.java:527)
	at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:264)
	at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:367)
	at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191)
	at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1105)
	at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:999)
	at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177)
	at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1283)
	at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1258)
	at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250)
	at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:77)
	at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:965)
	at com.google.auth.oauth2.UserCredentials.refreshAccessToken(UserCredentials.java:207)
	at com.google.auth.oauth2.OAuth2Credentials.refresh(OAuth2Credentials.java:149)
	at com.google.auth.oauth2.OAuth2Credentials.getRequestMetadata(OAuth2Credentials.java:135)
	at io.grpc.auth.GoogleAuthLibraryCallCredentials$1.run(GoogleAuthLibraryCallCredentials.java:110)
	... 3 common frames omitted

I wend deeper in the code and found that https://github.com/google/google-auth-library-java/blob/0fab63ca9798b78929e52d0313fe54241bda6256/oauth2_http/java/com/google/auth/oauth2/OAuth2Utils.java#L64 initializes with default parameters and without any possibility to configure proxy settings.

If you find it reasonable I would be glad to make PR.

Avoid depending on appengine-api-1.0-sdk

As @aozarov mentioned in #45, it'd be nice to avoid depending on appengine-api-1.0-sdk (17Mb jar) when not necessary.

Alternate options include:

  • Use "provided" or a like as a maven dependency
  • Use reflection to invoke methods on AppIdentityService. gcloud-java used to do the latter.

Cannot perform asynchronous refresh of access tokens prior to expiration.

The interface of OAuth2Credentials does not allow an external class to know the expiration time of the currently cached access token. This prevents implementation of asynchronous refresh patterns.

Currently callers must use

credentials.getRequestMetadata()

which will block if the token has expired. This is not ideal for high-performance clients.

Error:(1, 0) You appear to have guava-jdk5 on your project buildScript or buildSrc classpath. This is likely a transitive dependency of another gradle plugin.Run the buildEnvironment task to find out more. See https://issuetracker.google.com/38419426#comment8 for a workaround.

I get this error:
Error:(1, 0) You appear to have guava-jdk5 on your project buildScript or buildSrc classpath.
This is likely a transitive dependency of another gradle plugin.Run the buildEnvironment task to find out more.
See https://issuetracker.google.com/38419426#comment8 for a workaround.
Open File

My build.gradle is:

apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao'
apply plugin: 'com.google.firebase.firebase-crash'
apply plugin: 'me.tatarka.retrolambda'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.digitaldna.courier"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 3
        versionName "1.3"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }

    signingConfigs {
        debug {
            storeFile file("./debug.keystore")
            storePassword "android"
            keyAlias "androiddebugkey"
            keyPassword "android"
        }

        release {
            storeFile file("./debug.keystore")
            storePassword "android"
            keyAlias "androiddebugkey"
            keyPassword "android"
        }
    }

    buildTypes {
        debug {
            applicationIdSuffix ".debug"
            minifyEnabled false
            debuggable true
            signingConfig signingConfigs.debug
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            buildConfigField "String", "ENDPOINT", '"https://beta-api.1temiz.com"'
        }

        stage {
            applicationIdSuffix ".stage"
            minifyEnabled false
            debuggable true
            signingConfig signingConfigs.debug
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            buildConfigField "String", "ENDPOINT", '"https://api.1temiz.com"'
        }

        release {
            applicationIdSuffix ".prod"
            minifyEnabled true
            debuggable false
            signingConfig signingConfigs.release
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            buildConfigField "String", "ENDPOINT", '"https://api.1temiz.com"'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    // for jenkins
    packagingOptions {
        exclude 'META-INF/NOTICE' // It is not include NOTICE file
        exclude 'META-INF/LICENSE' // It is not include LICENSE file
    }

    // for jenkins
    lintOptions {
        abortOnError false
    }
}

dependencies {
    def supportLibraryVersion = "25.2.0"
    def retrofitVersion = "2.1.0"
    def playService = '10.2.0'
    def jacksonVersion = "2.8.6"

    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    testCompile 'junit:junit:4.12'

    // support library
    compile "com.android.support:appcompat-v7:$supportLibraryVersion"
    compile "com.android.support:design:$supportLibraryVersion"
    compile "com.android.support:support-v4:$supportLibraryVersion"
    compile "com.android.support:cardview-v7:$supportLibraryVersion"

    // retrofit
    compile "com.squareup.retrofit2:retrofit:$retrofitVersion"
    compile "com.squareup.retrofit2:converter-jackson:$retrofitVersion"
    compile "com.squareup.retrofit2:adapter-rxjava:$retrofitVersion"

    // Jackson
    compile "com.fasterxml.jackson.core:jackson-core:$jacksonVersion"
    compile "com.fasterxml.jackson.core:jackson-annotations:$jacksonVersion"
    compile "com.fasterxml.jackson.core:jackson-databind:$jacksonVersion"

    compile 'com.squareup.okhttp3:logging-interceptor:3.3.0'

    // rxjava
    compile 'io.reactivex:rxjava:1.1.6'
    compile 'io.reactivex:rxandroid:1.2.1'
    compile 'com.artemzin.rxjava:proguard-rules:1.1.0.0'

    // glide
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'jp.wasabeef:glide-transformations:2.0.1'

    // play services
    compile "com.google.android.gms:play-services-base:$playService"
    compile "com.google.android.gms:play-services-location:$playService"

    //firebase
    compile "com.google.firebase:firebase-core:$playService"
    compile "com.google.firebase:firebase-crash:$playService"
    compile "com.google.firebase:firebase-messaging:$playService"
    compile "com.google.firebase:firebase-appindexing:$playService"
    compile 'com.firebase:firebase-jobdispatcher:0.5.2'


    // multidex
    compile 'com.android.support:multidex:1.0.1'

    // stetho
    compile 'com.facebook.stetho:stetho:1.4.2'

    // google maps
    compile "com.google.android.gms:play-services-maps:$playService"

    //sticky header
    compile 'org.zakariya.stickyheaders:stickyheaders:0.7.6'

    // bootstrap includes
    compile project(path: ':core')
    compile project(path: ':mvp-loader')
    compile project(path: ':permissionmanager')
    compile project(path: ':validators')
    compile project(path: ':database')


    compile project(path: ':passwordindicator')
    compile project(path: ':orderstatus')
    compile project(path: ':notificationscount')
    compile project(path: ':lineweekchart')
    compile project(path: ':numbercircle')
}

apply plugin: 'com.google.gms.google-services'

There is https://stackoverflow.com/questions/47262150/commanderror-you-appear-to-have-guava-jdk5-on-your-project-buildscript-or-build
but its resolution doesn't work for me, I have "no classpath ('com.google.firebase:firebase-plugins:1.0.5') " to add "exclude group"
PLEASE HELP how to fix it.

Retry http failures in ServiceAccountCredentials.refreshAccessToken

As reported in googleapis/google-cloud-java#1545 , users have seen failures in ServiceAccountCredentials.refreshAccessToken, which has no retries on the http call. These failures should be retried.

java.io.IOException: Error getting access token for service account:
         at com.google.auth.oauth2.ServiceAccountCredentials.refreshAccessToken(ServiceAccountCredentials.java:319)
         at com.google.auth.oauth2.OAuth2Credentials.refresh(OAuth2Credentials.java:149)
         at com.google.auth.oauth2.OAuth2Credentials.getRequestMetadata(OAuth2Credentials.java:135)
         at com.google.auth.http.HttpCredentialsAdapter.initialize(HttpCredentialsAdapter.java:96)
         at com.google.cloud.HttpServiceOptions$1.initialize(HttpServiceOptions.java:224)
         at com.google.api.client.http.HttpRequestFactory.buildRequest(HttpRequestFactory.java:93)
         at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:423)
         at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
         at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
         at com.google.cloud.storage.spi.DefaultStorageRpc.create(DefaultStorageRpc.java:245)
         ... 10 more
 Caused by: java.net.SocketTimeoutException: connect timed out
  ...

DefaultCredentialsProvider caches failure for flaky Compute Engine credential lookup

Looking up application default credentials on a GCE VM can fail due to VM metadata server being unavailable during VM launch. This is a rare event but Google Cloud Dataflow customers hit this rare case one or two times a month due to the sheer number of VMs. GCE attempted to mitigate VM metadata server unavailability but were only able to reduce it be an order of magnitude thus we need support from the client to retry. Additionally, when contacting the GCE VM metadata server, we should be using the fixed IP address avoiding the nameserver lookup (another potential point of failure).

Problem area in the code:
https://github.com/google/google-auth-library-java/blob/b94f8e4d02bf6917af2e2f7ef8d7114a51dbcfa8/oauth2_http/java/com/google/auth/oauth2/DefaultCredentialsProvider.java#L261

Note that the code in this library and the Apiary auth support code are very similar. The fix was done within the Apiary auth code (note the use of the static IP address and also the presence of a fixed number of retries):
https://github.com/google/google-api-java-client/blob/4fc8c099d9db5646770868cc1bc9a33c9225b3c7/google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/OAuth2Utils.java#L74

It turned out that the fixes resulted in zero future customer contacts about this issue.

Support GCE_METADATA_HOST env var

The DefaultCredentialProvider in google-api-java-client allows for specifying the GCE metadata server address using the GCE_METADATA_HOST environment variable.

https://github.com/google/google-api-java-client/blob/dev/google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/OAuth2Utils.java#L110

The golang google cloud library seems to offer the same capability.

https://godoc.org/cloud.google.com/go/compute/metadata#Get

It would be useful if google-auth-library-java supported this as well.

The commit implementing this in google-api-java-client: googleapis/google-api-java-client@7bb680f

NPE because HTTP request initialized before setting URL

After updating google-auth-libraries to 0.3.0, we noticed the following stacktrace when using application default credentials:

com.google.gcloud.RetryHelper$NonRetriableException: java.lang.NullPointerException
    at com.google.gcloud.RetryHelper.doRetry(RetryHelper.java:193)
    at com.google.gcloud.RetryHelper.runWithRetries(RetryHelper.java:247)
    at com.google.gcloud.RetryHelper.runWithRetries(RetryHelper.java:237)
    at com.google.gcloud.storage.StorageImpl.listBuckets(StorageImpl.java:291)
    at com.google.gcloud.storage.StorageImpl.list(StorageImpl.java:285)
    at com.examples.example.Main.main(Main.java:19)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:293)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at com.google.auth.http.HttpCredentialsAdapter.initialize(HttpCredentialsAdapter.java:61)
    at com.google.gcloud.ServiceOptions$1.initialize(ServiceOptions.java:513)
    at com.google.api.client.http.HttpRequestFactory.buildRequest(HttpRequestFactory.java:93)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.buildHttpRequest(AbstractGoogleClientRequest.java:300)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
    at com.google.gcloud.spi.DefaultStorageRpc.list(DefaultStorageRpc.java:155)
    at com.google.gcloud.storage.StorageImpl$6.call(StorageImpl.java:295)
    at com.google.gcloud.storage.StorageImpl$6.call(StorageImpl.java:292)
    at com.google.gcloud.RetryHelper.doRetry(RetryHelper.java:181)

I think the issue was introduced in this commit. Also see https://github.com/google/google-auth-library-java/blame/master/oauth2_http/java/com/google/auth/http/HttpCredentialsAdapter.java#L61
The HTTP client's request factory seems to initialize the request before it sets the URL.

Make ComputeEngineCredentials support createScoped

The implementation of ComputeEngineCredentials does not support scope, which makes ComputeEngineCredential.createScoped not attach scope as expected. This is causing working with Drive scopes on GAE java8 and GCE receiving errors (e.g. this BigQuery auth issue) . Consider add support for scope in ComputeEngineCredentials.

FR: jwt validate

We should have some functionality to verify JWT's.

  1. General validation of jwt

  2. Validation of a Google JWT
    (Get and cache Google's certificates - validate: iss, iat?, & exp)

  3. Validation of a Firebase JWT
    (get and cache Firebase certificates, validate: iss, iat, & exp)

  4. Validate Identity provider tokens as well. (FB, Twitter, Github, etc.)

See https://github.com/auth0/java-jwt

JWT token + getRequestMetadata(entry point)

Credentials.getRequestMetadata(URI) is passed a URI defined as "the entry point for the request". What does that mean?

To be in sync with grpc/grpc#2911 and work with the current ServiceAccountJwtAccessCredentials, the URI passed would need to exclude the gRPC method name. But given the credential API, I would more expect the URI to be the request URI, which would include the method name.

Is it possible for "entry point" to be better defined?

FR: please give us a way to find Project ID

The other languages are trying to pickup current / default ProjectID - since SQL v2, bigtable, and other services require .

We possibly may need to get the default zone & region from gcloud config.

ServiceAccountCredentials permission Error when trying with Service Account

I am writing the below code to connect to a Pub-Sub Subscriber.

ServiceAccountCredentials servicecreds= ServiceAccountCredentials.fromStream(new FileInputStream("*.json"));
CredentialsProvider creds= FixedCredentialsProvider.create(servicecreds);
subscriber=Subscriber.newBuilder(subscription, new MessageReceiverExample()).setCredentialsProvider(creds).build();

I am getting "UnAuthenticatedException" when i am Trying to Listen via Subscriber. The code works if i use defaultApplicationCredentials(). But my requirement needs me to connect via the json file and not set Environment Variables.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.