1# Google Auth Library 2 3Open source authentication client library for Java. 4 5[](http://github.com/badges/stability-badges) 6[](https://img.shields.io/maven-central/v/com.google.auth/google-auth-library-credentials.svg) 7 8- [API Documentation](https://googleapis.dev/java/google-auth-library/latest) 9 10This project consists of 3 artifacts: 11 12- [*google-auth-library-credentials*](#google-auth-library-credentials): contains base classes and 13interfaces for Google credentials 14- [*google-auth-library-appengine*](#google-auth-library-appengine): contains App Engine 15credentials. This artifact depends on the App Engine SDK. 16- [*google-auth-library-oauth2-http*](#google-auth-library-oauth2-http): contains a wide variety of 17credentials as well as utility methods to create them and to get Application Default Credentials 18 19**Table of contents:** 20 21 22* [Quickstart](#quickstart) 23 24* [google-auth-library-oauth2-http](#google-auth-library-oauth2-http) 25 * [Application Default Credentials](#application-default-credentials) 26 * [ImpersonatedCredentials](#impersonatedcredentials) 27 * [Workload Identity Federation](#workload-identity-federation) 28 * [Accessing resources from AWS](#accessing-resources-from-aws) 29 * [Accessing resources from Azure](#access-resources-from-microsoft-azure) 30 * [Accessing resources from an OIDC identity provider](#accessing-resources-from-an-oidc-identity-provider) 31 * [Accessing resources using Executable-sourced credentials](#using-executable-sourced-credentials-with-oidc-and-saml) 32 * [Configurable Token Lifetime](#configurable-token-lifetime) 33 * [Workforce Identity Federation](#workforce-identity-federation) 34 * [Accessing resources using an OIDC or SAML 2.0 identity provider](#accessing-resources-using-an-oidc-or-saml-20-identity-provider) 35 * [Accessing resources using external account authorized user workforce credentials](#using-external-account-authorized-user-workforce-credentials) 36 * [Accessing resources using Executable-sourced credentials](#using-executable-sourced-workforce-credentials-with-oidc-and-saml) 37 * [Downscoping with Credential Access Boundaries](#downscoping-with-credential-access-boundaries) 38 * [Configuring a Proxy](#configuring-a-proxy) 39 * [Using Credentials with google-http-client](#using-credentials-with-google-http-client) 40 * [Verifying JWT Tokens](#verifying-a-signature) 41* [google-auth-library-credentials](#google-auth-library-credentials) 42* [google-auth-library-appengine](#google-auth-library-appengine) 43* [CI Status](#ci-status) 44* [Contributing](#contributing) 45* [License](#license) 46 47 48## Quickstart 49 50If you are using Maven, add this to your pom.xml file (notice that you can replace 51`google-auth-library-oauth2-http` with any of `google-auth-library-credentials` and 52`google-auth-library-appengine`, depending on your application needs): 53 54[//]: # ({x-version-update-start:google-auth-library-oauth2-http:released}) 55 56```xml 57<dependency> 58 <groupId>com.google.auth</groupId> 59 <artifactId>google-auth-library-oauth2-http</artifactId> 60 <version>1.19.0</version> 61</dependency> 62``` 63[//]: # ({x-version-update-end}) 64 65 66If you are using Gradle, add this to your dependencies 67 68[//]: # ({x-version-update-start:google-auth-library-oauth2-http:released}) 69```Groovy 70implementation 'com.google.auth:google-auth-library-oauth2-http:1.19.0' 71``` 72[//]: # ({x-version-update-end}) 73 74If you are using SBT, add this to your dependencies 75 76[//]: # ({x-version-update-start:google-auth-library-oauth2-http:released}) 77```Scala 78libraryDependencies += "com.google.auth" % "google-auth-library-oauth2-http" % "1.19.0" 79``` 80[//]: # ({x-version-update-end}) 81 82## google-auth-library-oauth2-http 83 84### Application Default Credentials 85 86This library provides an implementation of 87[Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials) 88for Java. Application Default Credentials provide a simple way to get authorization 89credentials for use in calling Google APIs. 90 91They are best suited for cases when the call needs to have the same identity and 92authorization level for the application independent of the user. This is the recommended 93approach to authorize calls to Cloud APIs, particularly when you're building an application 94that uses Google Cloud Platform. 95 96Application Default Credentials also support workload identity federation to access 97Google Cloud resources from non-Google Cloud platforms including Amazon Web Services (AWS), 98Microsoft Azure or any identity provider that supports OpenID Connect (OIDC). Workload 99identity federation is recommended for non-Google Cloud environments as it avoids the 100need to download, manage and store service account private keys locally, see: 101[Workload Identity Federation](#workload-identity-federation). 102 103#### Getting Application Default Credentials 104 105To get Application Default Credentials use `GoogleCredentials.getApplicationDefault()` or 106`GoogleCredentials.getApplicationDefault(HttpTransportFactory)`. These methods return the 107Application Default Credentials which are used to identify and authorize the whole application. The 108following are searched (in order) to find the Application Default Credentials: 109 1101. Credentials file pointed to by the `GOOGLE_APPLICATION_CREDENTIALS` environment variable 1112. Credentials provided by the Google Cloud SDK `gcloud auth application-default login` command 1123. Google App Engine built-in credentials 1134. Google Cloud Shell built-in credentials 1145. Google Compute Engine built-in credentials 115 - Skip this check by setting the environment variable `NO_GCE_CHECK=true` 116 - Customize the GCE metadata server address by setting the environment variable `GCE_METADATA_HOST=<hostname>` 117 118#### Explicit Credential Loading 119 120To get Credentials from a Service Account JSON key use `GoogleCredentials.fromStream(InputStream)` 121or `GoogleCredentials.fromStream(InputStream, HttpTransportFactory)`. Note that the credentials must 122be refreshed before the access token is available. 123 124```java 125GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream("/path/to/credentials.json")); 126credentials.refreshIfExpired(); 127AccessToken token = credentials.getAccessToken(); 128// OR 129AccessToken token = credentials.refreshAccessToken(); 130``` 131 132### ImpersonatedCredentials 133 134Allows a credentials issued to a user or service account to 135impersonate another. The source project using ImpersonatedCredentials must enable the 136"IAMCredentials" API. Also, the target service account must grant the orginating principal 137the "Service Account Token Creator" IAM role. 138 139```java 140String credPath = "/path/to/svc_account.json"; 141ServiceAccountCredentials sourceCredentials = ServiceAccountCredentials 142 .fromStream(new FileInputStream(credPath)); 143sourceCredentials = (ServiceAccountCredentials) sourceCredentials 144 .createScoped(Arrays.asList("https://www.googleapis.com/auth/iam")); 145 146ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create(sourceCredentials, 147 "[email protected]", null, 148 Arrays.asList("https://www.googleapis.com/auth/devstorage.read_only"), 300); 149 150Storage storage_service = StorageOptions.newBuilder().setProjectId("project-id") 151 .setCredentials(targetCredentials).build().getService(); 152 153for (Bucket b : storage_service.list().iterateAll()) 154 System.out.println(b); 155``` 156 157### Workload Identity Federation 158 159Using workload identity federation, your application can access Google Cloud resources from 160Amazon Web Services (AWS), Microsoft Azure, or any identity provider that supports OpenID Connect 161(OIDC). 162 163Traditionally, applications running outside Google Cloud have used service account keys to access 164Google Cloud resources. Using identity federation, your workload can impersonate a service account. 165This lets the external workload access Google Cloud resources directly, eliminating the maintenance 166and security burden associated with service account keys. 167 168#### Accessing resources from AWS 169 170In order to access Google Cloud resources from Amazon Web Services (AWS), the following requirements 171are needed: 172- A workload identity pool needs to be created. 173- AWS needs to be added as an identity provider in the workload identity pool (the Google [organization policy](https://cloud.google.com/iam/docs/manage-workload-identity-pools-providers#restrict) needs to allow federation from AWS). 174- Permission to impersonate a service account needs to be granted to the external identity. 175 176Follow the detailed [instructions](https://cloud.google.com/iam/docs/access-resources-aws) on how to 177configure workload identity federation from AWS. 178 179After configuring the AWS provider to impersonate a service account, a credential configuration file 180needs to be generated. Unlike service account credential files, the generated credential 181configuration file contains non-sensitive metadata to instruct the library on how to 182retrieve external subject tokens and exchange them for service account access tokens. 183The configuration file can be generated by using the [gcloud CLI](https://cloud.google.com/sdk/). 184 185To generate the AWS workload identity configuration, run the following command: 186 187```bash 188# Generate an AWS configuration file. 189gcloud iam workload-identity-pools create-cred-config \ 190 projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$AWS_PROVIDER_ID \ 191 --service-account $SERVICE_ACCOUNT_EMAIL \ 192 --aws \ 193 --output-file /path/to/generated/config.json 194``` 195 196Where the following variables need to be substituted: 197- `$PROJECT_NUMBER`: The Google Cloud project number. 198- `$POOL_ID`: The workload identity pool ID. 199- `$AWS_PROVIDER_ID`: The AWS provider ID. 200- `$SERVICE_ACCOUNT_EMAIL`: The email of the service account to impersonate. 201 202This generates the configuration file in the specified output file. 203 204If you are using [AWS IMDSv2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html), an additional flag `--enable-imdsv2` needs to be added to the `gcloud iam workload-identity-pools create-cred-config` command: 205 206```bash 207gcloud iam workload-identity-pools create-cred-config \ 208 projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$AWS_PROVIDER_ID \ 209 --service-account $SERVICE_ACCOUNT_EMAIL \ 210 --aws \ 211 --output-file /path/to/generated/config.json \ 212 --enable-imdsv2 213``` 214 215You can now [use the Auth library](#using-external-identities) to call Google Cloud 216resources from AWS. 217 218#### Access resources from Microsoft Azure 219 220In order to access Google Cloud resources from Microsoft Azure, the following requirements are 221needed: 222- A workload identity pool needs to be created. 223- Azure needs to be added as an identity provider in the workload identity pool (the Google [organization policy](https://cloud.google.com/iam/docs/manage-workload-identity-pools-providers#restrict) needs to allow federation from Azure). 224- The Azure tenant needs to be configured for identity federation. 225- Permission to impersonate a service account needs to be granted to the external identity. 226 227Follow the detailed [instructions](https://cloud.google.com/iam/docs/access-resources-azure) on how 228to configure workload identity federation from Microsoft Azure. 229 230After configuring the Azure provider to impersonate a service account, a credential configuration 231file needs to be generated. Unlike service account credential files, the generated credential 232configuration file contains non-sensitive metadata to instruct the library on how to 233retrieve external subject tokens and exchange them for service account access tokens. 234The configuration file can be generated by using the [gcloud CLI](https://cloud.google.com/sdk/). 235 236To generate the Azure workload identity configuration, run the following command: 237 238```bash 239# Generate an Azure configuration file. 240gcloud iam workload-identity-pools create-cred-config \ 241 projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$AZURE_PROVIDER_ID \ 242 --service-account $SERVICE_ACCOUNT_EMAIL \ 243 --azure \ 244 --output-file /path/to/generated/config.json 245``` 246 247Where the following variables need to be substituted: 248- `$PROJECT_NUMBER`: The Google Cloud project number. 249- `$POOL_ID`: The workload identity pool ID. 250- `$AZURE_PROVIDER_ID`: The Azure provider ID. 251- `$SERVICE_ACCOUNT_EMAIL`: The email of the service account to impersonate. 252 253This generates the configuration file in the specified output file. 254 255You can now [use the Auth library](#using-external-identities) to call Google Cloud 256resources from Azure. 257 258#### Accessing resources from an OIDC identity provider 259 260In order to access Google Cloud resources from an identity provider that supports [OpenID Connect (OIDC)](https://openid.net/connect/), the following requirements are needed: 261- A workload identity pool needs to be created. 262- An OIDC identity provider needs to be added in the workload identity pool (the Google [organization policy](https://cloud.google.com/iam/docs/manage-workload-identity-pools-providers#restrict) needs to allow federation from the identity provider). 263- Permission to impersonate a service account needs to be granted to the external identity. 264 265Follow the detailed [instructions](https://cloud.google.com/iam/docs/access-resources-oidc) on how 266to configure workload identity federation from an OIDC identity provider. 267 268After configuring the OIDC provider to impersonate a service account, a credential configuration 269file needs to be generated. Unlike service account credential files, the generated credential 270configuration file contains non-sensitive metadata to instruct the library on how to 271retrieve external subject tokens and exchange them for service account access tokens. 272The configuration file can be generated by using the [gcloud CLI](https://cloud.google.com/sdk/). 273 274For OIDC providers, the Auth library can retrieve OIDC tokens either from a local file location 275(file-sourced credentials) or from a local server (URL-sourced credentials). 276 277**File-sourced credentials** 278For file-sourced credentials, a background process needs to be continuously refreshing the file 279location with a new OIDC token prior to expiration. For tokens with one hour lifetimes, the token 280needs to be updated in the file every hour. The token can be stored directly as plain text or in 281JSON format. 282 283To generate a file-sourced OIDC configuration, run the following command: 284 285```bash 286# Generate an OIDC configuration file for file-sourced credentials. 287gcloud iam workload-identity-pools create-cred-config \ 288 projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$OIDC_PROVIDER_ID \ 289 --service-account $SERVICE_ACCOUNT_EMAIL \ 290 --credential-source-file $PATH_TO_OIDC_ID_TOKEN \ 291 # Optional arguments for file types. Default is "text": 292 # --credential-source-type "json" \ 293 # Optional argument for the field that contains the OIDC credential. 294 # This is required for json. 295 # --credential-source-field-name "id_token" \ 296 --output-file /path/to/generated/config.json 297``` 298 299Where the following variables need to be substituted: 300- `$PROJECT_NUMBER`: The Google Cloud project number. 301- `$POOL_ID`: The workload identity pool ID. 302- `$OIDC_PROVIDER_ID`: The OIDC provider ID. 303- `$SERVICE_ACCOUNT_EMAIL`: The email of the service account to impersonate. 304- `$PATH_TO_OIDC_ID_TOKEN`: The file path used to retrieve the OIDC token. 305 306This generates the configuration file in the specified output file. 307 308**URL-sourced credentials** 309For URL-sourced credentials, a local server needs to host a GET endpoint to return the OIDC token. 310The response can be in plain text or JSON. Additional required request headers can also be 311specified. 312 313To generate a URL-sourced OIDC workload identity configuration, run the following command: 314 315```bash 316# Generate an OIDC configuration file for URL-sourced credentials. 317gcloud iam workload-identity-pools create-cred-config \ 318 projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$OIDC_PROVIDER_ID \ 319 --service-account $SERVICE_ACCOUNT_EMAIL \ 320 --credential-source-url $URL_TO_GET_OIDC_TOKEN \ 321 --credential-source-headers $HEADER_KEY=$HEADER_VALUE \ 322 # Optional arguments for file types. Default is "text": 323 # --credential-source-type "json" \ 324 # Optional argument for the field that contains the OIDC credential. 325 # This is required for json. 326 # --credential-source-field-name "id_token" \ 327 --output-file /path/to/generated/config.json 328``` 329 330Where the following variables need to be substituted: 331- `$PROJECT_NUMBER`: The Google Cloud project number. 332- `$POOL_ID`: The workload identity pool ID. 333- `$OIDC_PROVIDER_ID`: The OIDC provider ID. 334- `$SERVICE_ACCOUNT_EMAIL`: The email of the service account to impersonate. 335- `$URL_TO_GET_OIDC_TOKEN`: The URL of the local server endpoint to call to retrieve the OIDC token. 336- `$HEADER_KEY` and `$HEADER_VALUE`: The additional header key/value pairs to pass along the GET 337request to `$URL_TO_GET_OIDC_TOKEN`, e.g. `Metadata-Flavor=Google`. 338 339You can now [use the Auth library](#using-external-identities) to call Google Cloud 340resources from an OIDC provider. 341 342#### Using Executable-sourced credentials with OIDC and SAML 343 344**Executable-sourced credentials** 345For executable-sourced credentials, a local executable is used to retrieve the 3rd party token. 346The executable must handle providing a valid, unexpired OIDC ID token or SAML assertion in JSON format 347to stdout. 348 349To use executable-sourced credentials, the `GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES` 350environment variable must be set to `1`. 351 352To generate an executable-sourced workload identity configuration, run the following command: 353 354```bash 355# Generate a configuration file for executable-sourced credentials. 356gcloud iam workload-identity-pools create-cred-config \ 357 projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$PROVIDER_ID \ 358 --service-account=$SERVICE_ACCOUNT_EMAIL \ 359 --subject-token-type=$SUBJECT_TOKEN_TYPE \ 360 # The absolute path for the program, including arguments. 361 # e.g. --executable-command="/path/to/command --foo=bar" 362 --executable-command=$EXECUTABLE_COMMAND \ 363 # Optional argument for the executable timeout. Defaults to 30s. 364 # --executable-timeout-millis=$EXECUTABLE_TIMEOUT \ 365 # Optional argument for the absolute path to the executable output file. 366 # See below on how this argument impacts the library behaviour. 367 # --executable-output-file=$EXECUTABLE_OUTPUT_FILE \ 368 --output-file /path/to/generated/config.json 369``` 370Where the following variables need to be substituted: 371- `$PROJECT_NUMBER`: The Google Cloud project number. 372- `$POOL_ID`: The workload identity pool ID. 373- `$PROVIDER_ID`: The OIDC or SAML provider ID. 374- `$SERVICE_ACCOUNT_EMAIL`: The email of the service account to impersonate. 375- `$SUBJECT_TOKEN_TYPE`: The subject token type. 376- `$EXECUTABLE_COMMAND`: The full command to run, including arguments. Must be an absolute path to the program. 377 378The `--executable-timeout-millis` flag is optional. This is the duration for which 379the auth library will wait for the executable to finish, in milliseconds. 380Defaults to 30 seconds when not provided. The maximum allowed value is 2 minutes. 381The minimum is 5 seconds. 382 383The `--executable-output-file` flag is optional. If provided, the file path must 384point to the 3PI credential response generated by the executable. This is useful 385for caching the credentials. By specifying this path, the Auth libraries will first 386check for its existence before running the executable. By caching the executable JSON 387response to this file, it improves performance as it avoids the need to run the executable 388until the cached credentials in the output file are expired. The executable must 389handle writing to this file - the auth libraries will only attempt to read from 390this location. The format of contents in the file should match the JSON format 391expected by the executable shown below. 392 393To retrieve the 3rd party token, the library will call the executable 394using the command specified. The executable's output must adhere to the response format 395specified below. It must output the response to stdout. 396 397A sample successful executable OIDC response: 398```json 399{ 400 "version": 1, 401 "success": true, 402 "token_type": "urn:ietf:params:oauth:token-type:id_token", 403 "id_token": "HEADER.PAYLOAD.SIGNATURE", 404 "expiration_time": 1620499962 405} 406``` 407 408A sample successful executable SAML response: 409```json 410{ 411 "version": 1, 412 "success": true, 413 "token_type": "urn:ietf:params:oauth:token-type:saml2", 414 "saml_response": "...", 415 "expiration_time": 1620499962 416} 417``` 418A sample executable error response: 419```json 420{ 421 "version": 1, 422 "success": false, 423 "code": "401", 424 "message": "Caller not authorized." 425} 426``` 427These are all required fields for an error response. The code and message 428fields will be used by the library as part of the thrown exception. 429 430For successful responses, the `expiration_time` field is only required 431when an output file is specified in the credential configuration. 432 433Response format fields summary: 434 * `version`: The version of the JSON output. Currently only version 1 is supported. 435 * `success`: When true, the response must contain the 3rd party token and token type. The response must also contain 436 the expiration_time field if an output file was specified in the credential configuration. The executable must also 437 exit with exit code 0. When false, the response must contain the error code and message fields and exit with a 438 non-zero value. 439 * `token_type`: The 3rd party subject token type. Must be *urn:ietf:params:oauth:token-type:jwt*, 440 *urn:ietf:params:oauth:token-type:id_token*, or *urn:ietf:params:oauth:token-type:saml2*. 441 * `id_token`: The 3rd party OIDC token. 442 * `saml_response`: The 3rd party SAML response. 443 * `expiration_time`: The 3rd party subject token expiration time in seconds (unix epoch time). 444 * `code`: The error code string. 445 * `message`: The error message. 446 447All response types must include both the `version` and `success` fields. 448 * Successful responses must include the `token_type` and one of 449 `id_token` or `saml_response`. The `expiration_time` field must also be present if an output file was specified in 450 the credential configuration. 451 * Error responses must include both the `code` and `message` fields. 452 453The library will populate the following environment variables when the executable is run: 454 * `GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE`: The audience field from the credential configuration. Always present. 455 * `GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE`: This expected subject token type. Always present. 456 * `GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL`: The service account email. Only present when service account impersonation is used. 457 * `GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE`: The output file location from the credential configuration. Only present when specified in the credential configuration. 458 459These environment variables can be used by the executable to avoid hard-coding these values. 460 461##### Security considerations 462The following security practices are highly recommended: 463 * 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. 464 * The configuration file should not be modifiable. Write access should be restricted to avoid processes modifying the executable command portion. 465 466Given the complexity of using executable-sourced credentials, it is recommended to use 467the existing supported mechanisms (file-sourced/URL-sourced) for providing 3rd party 468credentials unless they do not meet your specific requirements. 469 470You can now [use the Auth library](#using-external-identities) to call Google Cloud 471resources from an OIDC or SAML provider. 472 473#### Configurable Token Lifetime 474When 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. 475 476To 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): 477 ```bash 478 # Generate an AWS configuration file with configurable token lifetime. 479 gcloud iam workload-identity-pools create-cred-config \ 480 projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$AWS_PROVIDER_ID \ 481 --service-account $SERVICE_ACCOUNT_EMAIL \ 482 --aws \ 483 --output-file /path/to/generated/config.json \ 484 --service-account-token-lifetime-seconds $TOKEN_LIFETIME 485 ``` 486 487Where the following variables need to be substituted: 488- `$PROJECT_NUMBER`: The Google Cloud project number. 489- `$POOL_ID`: The workload identity pool ID. 490- `$AWS_PROVIDER_ID`: The AWS provider ID. 491- `$SERVICE_ACCOUNT_EMAIL`: The email of the service account to impersonate. 492- `$TOKEN_LIFETIME`: The desired lifetime duration of the service account access token in seconds. 493 494The `service-account-token-lifetime-seconds` flag is optional. If not provided, this defaults to one hour. 495The minimum allowed value is 600 (10 minutes) and the maximum allowed value is 43200 (12 hours). 496If 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. 497 498Note 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. 499 500### Workforce Identity Federation 501 502[Workforce identity federation](https://cloud.google.com/iam/docs/workforce-identity-federation) lets you use an 503external identity provider (IdP) to authenticate and authorize a workforce—a group of users, such as employees, 504partners, and contractors—using IAM, so that the users can access Google Cloud services. Workforce identity federation 505extends Google Cloud's identity capabilities to support syncless, attribute-based single sign on. 506 507With workforce identity federation, your workforce can access Google Cloud resources using an external 508identity provider (IdP) that supports OpenID Connect (OIDC) or SAML 2.0 such as Azure Active Directory (Azure AD), 509Active Directory Federation Services (AD FS), Okta, and others. 510 511#### Accessing resources using an OIDC or SAML 2.0 identity provider 512 513In order to access Google Cloud resources from an identity provider that supports [OpenID Connect (OIDC)](https://openid.net/connect/), 514the following requirements are needed: 515- A workforce identity pool needs to be created. 516- An OIDC or SAML 2.0 identity provider needs to be added in the workforce pool. 517 518Follow the detailed [instructions](https://cloud.google.com/iam/docs/configuring-workforce-identity-federation) on how 519to configure workforce identity federation. 520 521After configuring an OIDC or SAML 2.0 provider, a credential configuration 522file needs to be generated. The generated credential configuration file contains non-sensitive metadata to instruct the 523library on how to retrieve external subject tokens and exchange them for GCP access tokens. 524The configuration file can be generated by using the [gcloud CLI](https://cloud.google.com/sdk/). 525 526The Auth library can retrieve external subject tokens from a local file location 527(file-sourced credentials), from a local server (URL-sourced credentials) or by calling an executable 528(executable-sourced credentials). 529 530**File-sourced credentials** 531For file-sourced credentials, a background process needs to be continuously refreshing the file 532location with a new subject token prior to expiration. For tokens with one hour lifetimes, the token 533needs to be updated in the file every hour. The token can be stored directly as plain text or in 534JSON format. 535 536To generate a file-sourced OIDC configuration, run the following command: 537 538```bash 539# Generate an OIDC configuration file for file-sourced credentials. 540gcloud iam workforce-pools create-cred-config \ 541 locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ 542 --subject-token-type=urn:ietf:params:oauth:token-type:id_token \ 543 --credential-source-file=$PATH_TO_OIDC_ID_TOKEN \ 544 --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ 545 # Optional arguments for file types. Default is "text": 546 # --credential-source-type "json" \ 547 # Optional argument for the field that contains the OIDC credential. 548 # This is required for json. 549 # --credential-source-field-name "id_token" \ 550 --output-file=/path/to/generated/config.json 551``` 552Where the following variables need to be substituted: 553- `$WORKFORCE_POOL_ID`: The workforce pool ID. 554- `$PROVIDER_ID`: The provider ID. 555- `$PATH_TO_OIDC_ID_TOKEN`: The file path used to retrieve the OIDC token. 556- `$WORKFORCE_POOL_USER_PROJECT`: The project number associated with the [workforce pools user project](https://cloud.google.com/iam/docs/workforce-identity-federation#workforce-pools-user-project). 557 558To generate a file-sourced SAML configuration, run the following command: 559 560```bash 561# Generate a SAML configuration file for file-sourced credentials. 562gcloud iam workforce-pools create-cred-config \ 563 locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ 564 --credential-source-file=$PATH_TO_SAML_ASSERTION \ 565 --subject-token-type=urn:ietf:params:oauth:token-type:saml2 \ 566 --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ 567 --output-file=/path/to/generated/config.json 568``` 569 570Where the following variables need to be substituted: 571- `$WORKFORCE_POOL_ID`: The workforce pool ID. 572- `$PROVIDER_ID`: The provider ID. 573- `$PATH_TO_SAML_ASSERTION`: The file path used to retrieve the base64-encoded SAML assertion. 574- `$WORKFORCE_POOL_USER_PROJECT`: The project number associated with the [workforce pools user project](https://cloud.google.com/iam/docs/workforce-identity-federation#workforce-pools-user-project). 575 576These commands generate the configuration file in the specified output file. 577 578**URL-sourced credentials** 579For URL-sourced credentials, a local server needs to host a GET endpoint to return the OIDC token. 580The response can be in plain text or JSON. Additional required request headers can also be 581specified. 582 583To generate a URL-sourced OIDC workforce identity configuration, run the following command: 584 585```bash 586# Generate an OIDC configuration file for URL-sourced credentials. 587gcloud iam workforce-pools create-cred-config \ 588 locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ 589 --subject-token-type=urn:ietf:params:oauth:token-type:id_token \ 590 --credential-source-url=$URL_TO_RETURN_OIDC_ID_TOKEN \ 591 --credential-source-headers $HEADER_KEY=$HEADER_VALUE \ 592 --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ 593 --output-file=/path/to/generated/config.json 594``` 595 596Where the following variables need to be substituted: 597- `$WORKFORCE_POOL_ID`: The workforce pool ID. 598- `$PROVIDER_ID`: The provider ID. 599- `$URL_TO_RETURN_OIDC_ID_TOKEN`: The URL of the local server endpoint. 600- `$HEADER_KEY` and `$HEADER_VALUE`: The additional header key/value pairs to pass along the GET request to 601 `$URL_TO_GET_OIDC_TOKEN`, e.g. `Metadata-Flavor=Google`. 602- `$WORKFORCE_POOL_USER_PROJECT`: The project number associated with the [workforce pools user project](https://cloud.google.com/iam/docs/workforce-identity-federation#workforce-pools-user-project). 603 604To generate a URL-sourced SAML configuration, run the following command: 605 606```bash 607# Generate a SAML configuration file for file-sourced credentials. 608gcloud iam workforce-pools create-cred-config \ 609 locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ 610 --subject-token-type=urn:ietf:params:oauth:token-type:saml2 \ 611 --credential-source-url=$URL_TO_GET_SAML_ASSERTION \ 612 --credential-source-headers $HEADER_KEY=$HEADER_VALUE \ 613 --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ 614 --output-file=/path/to/generated/config.json 615``` 616 617These commands generate the configuration file in the specified output file. 618 619Where the following variables need to be substituted: 620- `$WORKFORCE_POOL_ID`: The workforce pool ID. 621- `$PROVIDER_ID`: The provider ID. 622- `$URL_TO_GET_SAML_ASSERTION`: The URL of the local server endpoint. 623- `$HEADER_KEY` and `$HEADER_VALUE`: The additional header key/value pairs to pass along the GET request to 624 `$URL_TO_GET_SAML_ASSERTION`, e.g. `Metadata-Flavor=Google`. 625- `$WORKFORCE_POOL_USER_PROJECT`: The project number associated with the [workforce pools user project](https://cloud.google.com/iam/docs/workforce-identity-federation#workforce-pools-user-project). 626 627#### Using external account authorized user workforce credentials 628 629[External account authorized user credentials](https://cloud.google.com/iam/docs/workforce-obtaining-short-lived-credentials#browser-based-sign-in) allow you to sign in with a web browser to an external identity provider account via the 630gcloud CLI and create a configuration for the auth library to use. 631 632To generate an external account authorized user workforce identity configuration, run the following command: 633 634```bash 635gcloud auth application-default login --login-config=$LOGIN_CONFIG 636``` 637 638Where the following variable needs to be substituted: 639- `$LOGIN_CONFIG`: The login config file generated with the cloud console or 640 [gcloud iam workforce-pools create-login-config](https://cloud.google.com/sdk/gcloud/reference/iam/workforce-pools/create-login-config) 641 642This will open a browser flow for you to sign in via the configured third party identity provider 643and then will store the external account authorized user configuration at the well known ADC location. 644The auth library will then use the provided refresh token from the configuration to generate and refresh 645an access token to call Google Cloud services. 646 647Note 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. 648The lifetime can be modified by changing the [session duration of the workforce pool](https://cloud.google.com/iam/docs/reference/rest/v1/locations.workforcePools), and can be set as high as 12 hours. 649 650#### Using Executable-sourced workforce credentials with OIDC and SAML 651 652**Executable-sourced credentials** 653For executable-sourced credentials, a local executable is used to retrieve the 3rd party token. 654The executable must handle providing a valid, unexpired OIDC ID token or SAML assertion in JSON format 655to stdout. 656 657To use executable-sourced credentials, the `GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES` 658environment variable must be set to `1`. 659 660To generate an executable-sourced workforce identity configuration, run the following command: 661 662```bash 663# Generate a configuration file for executable-sourced credentials. 664gcloud iam workforce-pools create-cred-config \ 665 locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ 666 --subject-token-type=$SUBJECT_TOKEN_TYPE \ 667 # The absolute path for the program, including arguments. 668 # e.g. --executable-command="/path/to/command --foo=bar" 669 --executable-command=$EXECUTABLE_COMMAND \ 670 # Optional argument for the executable timeout. Defaults to 30s. 671 # --executable-timeout-millis=$EXECUTABLE_TIMEOUT \ 672 # Optional argument for the absolute path to the executable output file. 673 # See below on how this argument impacts the library behaviour. 674 # --executable-output-file=$EXECUTABLE_OUTPUT_FILE \ 675 --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ 676 --output-file /path/to/generated/config.json 677``` 678Where the following variables need to be substituted: 679- `$WORKFORCE_POOL_ID`: The workforce pool ID. 680- `$PROVIDER_ID`: The provider ID. 681- `$SUBJECT_TOKEN_TYPE`: The subject token type. 682- `$EXECUTABLE_COMMAND`: The full command to run, including arguments. Must be an absolute path to the program. 683- `$WORKFORCE_POOL_USER_PROJECT`: The project number associated with the [workforce pools user project](https://cloud.google.com/iam/docs/workforce-identity-federation#workforce-pools-user-project). 684 685The `--executable-timeout-millis` flag is optional. This is the duration for which 686the auth library will wait for the executable to finish, in milliseconds. 687Defaults to 30 seconds when not provided. The maximum allowed value is 2 minutes. 688The minimum is 5 seconds. 689 690The `--executable-output-file` flag is optional. If provided, the file path must 691point to the 3rd party credential response generated by the executable. This is useful 692for caching the credentials. By specifying this path, the Auth libraries will first 693check for its existence before running the executable. By caching the executable JSON 694response to this file, it improves performance as it avoids the need to run the executable 695until the cached credentials in the output file are expired. The executable must 696handle writing to this file - the auth libraries will only attempt to read from 697this location. The format of contents in the file should match the JSON format 698expected by the executable shown below. 699 700To retrieve the 3rd party token, the library will call the executable 701using the command specified. The executable's output must adhere to the response format 702specified below. It must output the response to stdout. 703 704Refer to the [using executable-sourced credentials with Workload Identity Federation](#using-executable-sourced-credentials-with-oidc-and-saml) 705above for the executable response specification. 706 707##### Security considerations 708The following security practices are highly recommended: 709* 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. 710* The configuration file should not be modifiable. Write access should be restricted to avoid processes modifying the executable command portion. 711 712Given the complexity of using executable-sourced credentials, it is recommended to use 713the existing supported mechanisms (file-sourced/URL-sourced) for providing 3rd party 714credentials unless they do not meet your specific requirements. 715 716You can now [use the Auth library](#using-external-identities) to call Google Cloud 717resources from an OIDC or SAML provider. 718 719### Using External Identities 720 721External identities can be used with `Application Default Credentials`. In order to use external identities with 722Application Default Credentials, you need to generate the JSON credentials configuration file for your external identity 723as described above. Once generated, store the path to this file in the`GOOGLE_APPLICATION_CREDENTIALS` environment variable. 724 725```bash 726export GOOGLE_APPLICATION_CREDENTIALS=/path/to/config.json 727``` 728 729The library can now choose the right type of client and initialize credentials from the context 730provided in the configuration file. 731 732```java 733GoogleCredentials googleCredentials = GoogleCredentials.getApplicationDefault(); 734 735String projectId = "your-project-id"; 736String url = "https://storage.googleapis.com/storage/v1/b?project=" + projectId; 737 738HttpCredentialsAdapter credentialsAdapter = new HttpCredentialsAdapter(googleCredentials); 739HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory(credentialsAdapter); 740HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(url)); 741 742JsonObjectParser parser = new JsonObjectParser(GsonFactory.getDefaultInstance()); 743request.setParser(parser); 744 745HttpResponse response = request.execute(); 746System.out.println(response.parseAsString()); 747``` 748 749You can also explicitly initialize external account clients using the generated configuration file. 750 751```java 752ExternalAccountCredentials credentials = 753 ExternalAccountCredentials.fromStream(new FileInputStream("/path/to/credentials.json")); 754``` 755 756##### Security Considerations 757Note that this library does not perform any validation on the token_url, token_info_url, 758or service_account_impersonation_url fields of the credential configuration. 759It is not recommended to use a credential configuration that you did not 760generate with the gcloud CLI unless you verify that the URL fields point to a 761googleapis.com domain. 762 763### Downscoping with Credential Access Boundaries 764 765[Downscoping with Credential Access Boundaries](https://cloud.google.com/iam/docs/downscoping-short-lived-credentials) 766enables the ability to downscope, or restrict, the Identity and Access Management (IAM) permissions 767that a short-lived credential can use for Cloud Storage. 768 769The `DownscopedCredentials` class can be used to produce a downscoped access token from a 770`CredentialAccessBoundary` and a source credential. The Credential Access Boundary specifies which 771resources the newly created credential can access, as well as an upper bound on the permissions that 772are available on each resource. Using downscoped credentials ensures tokens in flight always have 773the least privileges (Principle of Least Privilege). 774 775The snippet below shows how to initialize a CredentialAccessBoundary with one AccessBoundaryRule 776which specifies that the downscoped token will have readonly access to objects starting with 777"customer-a" in bucket "bucket-123": 778```java 779// Create the AccessBoundaryRule. 780String availableResource = "//storage.googleapis.com/projects/_/buckets/bucket-123"; 781String availablePermission = "inRole:roles/storage.objectViewer"; 782String expression = "resource.name.startsWith('projects/_/buckets/bucket-123/objects/customer-a')"; 783 784CredentialAccessBoundary.AccessBoundaryRule rule = 785 CredentialAccessBoundary.AccessBoundaryRule.newBuilder() 786 .setAvailableResource(availableResource) 787 .addAvailablePermission(availablePermission) 788 .setAvailabilityCondition( 789 CredentialAccessBoundary.AccessBoundaryRule.AvailabilityCondition.newBuilder().setExpression(expression).build()) 790 .build(); 791 792// Create the CredentialAccessBoundary with the rule. 793CredentialAccessBoundary credentialAccessBoundary = 794 CredentialAccessBoundary.newBuilder().addRule(rule).build(); 795``` 796 797The common pattern of usage is to have a token broker with elevated access generate these downscoped 798credentials from higher access source credentials and pass the downscoped short-lived access tokens 799to a token consumer via some secure authenticated channel for limited access to Google Cloud Storage 800resources. 801 802Using the CredentialAccessBoundary created above in the Token Broker: 803```java 804// Retrieve the source credentials from ADC. 805GoogleCredentials sourceCredentials = GoogleCredentials.getApplicationDefault() 806 .createScoped("https://www.googleapis.com/auth/cloud-platform"); 807 808// Initialize the DownscopedCredentials class. 809DownscopedCredentials downscopedCredentials = 810 DownscopedCredentials.newBuilder() 811 .setSourceCredential(credentials) 812 .setCredentialAccessBoundary(credentialAccessBoundary) 813 .build(); 814 815// Retrieve the downscoped access token. 816// This will need to be passed to the Token Consumer. 817AccessToken downscopedAccessToken = downscopedCredentials.refreshAccessToken(); 818``` 819 820A token broker can be set up on a server in a private network. Various workloads 821(token consumers) in the same network will send authenticated requests to that broker for downscoped 822tokens to access or modify specific google cloud storage buckets. 823 824The broker will instantiate downscoped credentials instances that can be used to generate short 825lived downscoped access tokens which will be passed to the token consumer. 826 827Putting it all together: 828```java 829// Retrieve the source credentials from ADC. 830GoogleCredentials sourceCredentials = GoogleCredentials.getApplicationDefault() 831 .createScoped("https://www.googleapis.com/auth/cloud-platform"); 832 833// Create an Access Boundary Rule which will restrict the downscoped token to having readonly 834// access to objects starting with "customer-a" in bucket "bucket-123". 835String availableResource = "//storage.googleapis.com/projects/_/buckets/bucket-123"; 836String availablePermission = "inRole:roles/storage.objectViewer"; 837String expression = "resource.name.startsWith('projects/_/buckets/bucket-123/objects/customer-a')"; 838 839CredentialAccessBoundary.AccessBoundaryRule rule = 840 CredentialAccessBoundary.AccessBoundaryRule.newBuilder() 841 .setAvailableResource(availableResource) 842 .addAvailablePermission(availablePermission) 843 .setAvailabilityCondition( 844 new AvailabilityCondition(expression, /* title= */ null, /* description= */ null)) 845 .build(); 846 847// Initialize the DownscopedCredentials class. 848DownscopedCredentials downscopedCredentials = 849 DownscopedCredentials.newBuilder() 850 .setSourceCredential(credentials) 851 .setCredentialAccessBoundary(CredentialAccessBoundary.newBuilder().addRule(rule).build()) 852 .build(); 853 854// Retrieve the downscoped access token. 855// This will need to be passed to the Token Consumer. 856AccessToken downscopedAccessToken = downscopedCredentials.refreshAccessToken(); 857``` 858 859These downscoped access tokens can be used by the Token Consumer via `OAuth2Credentials` or 860`OAuth2CredentialsWithRefresh`. This credential can then be used to initialize a storage client 861instance to access Google Cloud Storage resources with restricted access. 862 863```java 864// You can pass an `OAuth2RefreshHandler` to `OAuth2CredentialsWithRefresh` which will allow the 865// library to seamlessly handle downscoped token refreshes on expiration. 866OAuth2CredentialsWithRefresh.OAuth2RefreshHandler handler = 867 new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { 868 @Override 869 public AccessToken refreshAccessToken() { 870 // Add the logic here that retrieves the token from your Token Broker. 871 return accessToken; 872 } 873}; 874 875// Downscoped token retrieved from token broker. 876AccessToken downscopedToken = handler.refreshAccessToken(); 877 878// Build the OAuth2CredentialsWithRefresh from the downscoped token and pass a refresh handler 879// to handle token expiration. Passing the original downscoped token or the expiry here is optional, 880// as the refresh_handler will generate the downscoped token on demand. 881OAuth2CredentialsWithRefresh credentials = 882 OAuth2CredentialsWithRefresh.newBuilder() 883 .setAccessToken(downscopedToken) 884 .setRefreshHandler(handler) 885 .build(); 886 887// Use the credentials with the Cloud Storage SDK. 888StorageOptions options = StorageOptions.newBuilder().setCredentials(credentials).build(); 889Storage storage = options.getService(); 890 891// Call GCS APIs. 892// Since we passed the downscoped credential, we will have have limited readonly access to objects 893// starting with "customer-a" in bucket "bucket-123". 894storage.get(...) 895``` 896 897Note: Only Cloud Storage supports Credential Access Boundaries. Other Google Cloud services do not 898support this feature. 899 900## Configuring a Proxy 901 902For HTTP clients, a basic proxy can be configured by using `http.proxyHost` and related system properties as documented 903by [Java Networking and Proxies](https://docs.oracle.com/javase/8/docs/technotes/guides/net/proxies.html). 904 905For a more custom proxy (e.g. for an authenticated proxy), provide a custom 906[`HttpTransportFactory`][http-transport-factory] to [`GoogleCredentials`][google-credentials]: 907 908```java 909import com.google.api.client.http.HttpTransport; 910import com.google.api.client.http.apache.v2.ApacheHttpTransport; 911import com.google.auth.http.HttpTransportFactory; 912import com.google.auth.oauth2.GoogleCredentials; 913import org.apache.http.HttpHost; 914import org.apache.http.auth.AuthScope; 915import org.apache.http.auth.UsernamePasswordCredentials; 916import org.apache.http.client.CredentialsProvider; 917import org.apache.http.client.HttpClient; 918import org.apache.http.conn.routing.HttpRoutePlanner; 919import org.apache.http.impl.client.BasicCredentialsProvider; 920import org.apache.http.impl.client.ProxyAuthenticationStrategy; 921import org.apache.http.impl.conn.DefaultProxyRoutePlanner; 922 923import java.io.IOException; 924 925public class ProxyExample { 926 public GoogleCredentials getCredentials() throws IOException { 927 HttpTransportFactory httpTransportFactory = getHttpTransportFactory( 928 "some-host", 8080, "some-username", "some-password" 929 ); 930 931 return GoogleCredentials.getApplicationDefault(httpTransportFactory); 932 } 933 934 public HttpTransportFactory getHttpTransportFactory(String proxyHost, int proxyPort, String proxyUsername, String proxyPassword) { 935 HttpHost proxyHostDetails = new HttpHost(proxyHost, proxyPort); 936 HttpRoutePlanner httpRoutePlanner = new DefaultProxyRoutePlanner(proxyHostDetails); 937 938 CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); 939 credentialsProvider.setCredentials( 940 new AuthScope(proxyHostDetails.getHostName(), proxyHostDetails.getPort()), 941 new UsernamePasswordCredentials(proxyUsername, proxyPassword) 942 ); 943 944 HttpClient httpClient = ApacheHttpTransport.newDefaultHttpClientBuilder() 945 .setRoutePlanner(httpRoutePlanner) 946 .setProxyAuthenticationStrategy(ProxyAuthenticationStrategy.INSTANCE) 947 .setDefaultCredentialsProvider(credentialsProvider) 948 .build(); 949 950 final HttpTransport httpTransport = new ApacheHttpTransport(httpClient); 951 return new HttpTransportFactory() { 952 @Override 953 public HttpTransport create() { 954 return httpTransport; 955 } 956 }; 957 } 958} 959``` 960 961The above example requires `com.google.http-client:google-http-client-apache-v2`. 962 963## Using Credentials with `google-http-client` 964 965Credentials provided by [com.google.auth:google-auth-library-oauth2-http]( 966https://search.maven.org/artifact/com.google.auth/google-auth-library-oauth2-http) 967can be used with Google's [HTTP-based clients][apiary-clients]. 968We provide a [`HttpCredentialsAdapter`][http-credentials-adapter] which can be used 969as an [`HttpRequestInitializer`][http-request-initializer], the last argument for 970their builders. 971 972```java 973import com.google.api.client.http.HttpRequestInitializer; 974import com.google.api.services.bigquery.Bigquery; 975import com.google.auth.http.HttpCredentialsAdapter; 976import com.google.auth.oauth2.GoogleCredentials; 977 978GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); 979HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials); 980 981Bigquery bq = new Bigquery.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer) 982 .setApplicationName(APPLICATION_NAME) 983 .build(); 984``` 985 986## Verifying JWT Tokens (Beta) 987 988To verify a JWT token, use the [`TokenVerifier`][token-verifier] class. 989 990### Verifying a Signature 991 992To verify a signature, use the default [`TokenVerifier`][token-verifier]: 993 994```java 995import com.google.api.client.json.webtoken.JsonWebSignature; 996import com.google.auth.oauth2.TokenVerifier; 997 998TokenVerifier tokenVerifier = TokenVerifier.newBuilder().build(); 999try { 1000 JsonWebSignature jsonWebSignature = tokenVerifier.verify(tokenString); 1001 // optionally verify additional claims 1002 if (!"expected-value".equals(jsonWebSignature.getPayload().get("additional-claim"))) { 1003 // handle custom verification error 1004 } 1005} catch (TokenVerifier.VerificationException e) { 1006 // invalid token 1007} 1008``` 1009 1010### Customizing the TokenVerifier 1011 1012To customize a [`TokenVerifier`][token-verifier], instantiate it via its builder: 1013 1014```java 1015import com.google.api.client.json.webtoken.JsonWebSignature; 1016import com.google.auth.oauth2.TokenVerifier; 1017 1018TokenVerifier tokenVerifier = TokenVerifier.newBuilder() 1019 .setAudience("audience-to-verify") 1020 .setIssuer("issuer-to-verify") 1021 .build(); 1022try { 1023 JsonWebSignature jsonWebSignature = tokenVerifier.verify(tokenString); 1024 // optionally verify additional claims 1025 if (!"expected-value".equals(jsonWebSignature.getPayload().get("additional-claim"))) { 1026 // handle custom verification error 1027 } 1028} catch (TokenVerifier.VerificationException e) { 1029 // invalid token 1030} 1031``` 1032 1033For more options, see the [`TokenVerifier.Builder`][token-verifier-builder] documentation. 1034 1035 1036## google-auth-library-credentials 1037 1038This artifact contains base classes and interfaces for Google credentials: 1039- `Credentials`: base class for an authorized identity. Implementations of this class can be used to 1040 authorize your application 1041- `RequestMetadataCallback`: interface for the callback that receives the result of the asynchronous 1042 `Credentials.getRequestMetadata(URI, Executor, RequestMetadataCallback)` 1043- `ServiceAccountSigner`: interface for a service account signer. Implementations of this class are 1044 capable of signing byte arrays using the credentials associated to a Google Service Account 1045 1046## google-auth-library-appengine 1047 1048This artifact depends on the App Engine SDK (`appengine-api-1.0-sdk`) and should be used only by 1049applications running on App Engine environments that use urlfetch. The `AppEngineCredentials` class 1050allows you to authorize your App Engine application given an instance of 1051[AppIdentityService][appengine-app-identity-service]. 1052 1053Usage: 1054 1055```java 1056import com.google.appengine.api.appidentity.AppIdentityService; 1057import com.google.appengine.api.appidentity.AppIdentityServiceFactory; 1058import com.google.auth.Credentials; 1059import com.google.auth.appengine.AppEngineCredentials; 1060 1061AppIdentityService appIdentityService = AppIdentityServiceFactory.getAppIdentityService(); 1062 1063Credentials credentials = 1064 AppEngineCredentials.newBuilder() 1065 .setScopes(...) 1066 .setAppIdentityService(appIdentityService) 1067 .build(); 1068``` 1069 1070**Important: `com.google.auth.appengine.AppEngineCredentials` is a separate class from 1071`com.google.auth.oauth2.AppEngineCredentials`.** 1072 1073## CI Status 1074 1075Java Version | Status 1076------------ | ------ 1077Java 8 | [](http://storage.googleapis.com/cloud-devrel-public/java/badges/google-auth-library-java/java8.html) 1078Java 8 OSX | [](http://storage.googleapis.com/cloud-devrel-public/java/badges/google-auth-library-java/java8-osx.html) 1079Java 8 Windows | [](http://storage.googleapis.com/cloud-devrel-public/java/badges/google-auth-library-java/java8-win.html) 1080Java 11 | [](http://storage.googleapis.com/cloud-devrel-public/java/badges/google-auth-library-java/java11.html) 1081 1082## Contributing 1083 1084Contributions to this library are always welcome and highly encouraged. 1085 1086See [CONTRIBUTING](CONTRIBUTING.md) documentation for more information on how to get started. 1087 1088Please note that this project is released with a Contributor Code of Conduct. By participating in 1089this project you agree to abide by its terms. See [Code of Conduct](CODE_OF_CONDUCT.md) for more 1090information. 1091 1092## Running the Tests 1093 1094To run the tests you will need: 1095 1096* Maven 3+ 1097 1098```bash 1099$ mvn test 1100``` 1101 1102## License 1103 1104BSD 3-Clause - See [LICENSE](LICENSE) for more information. 1105 1106[appengine-sdk-versions]: https://search.maven.org/search?q=g:com.google.appengine%20AND%20a:appengine-api-1.0-sdk&core=gav 1107[appengine-sdk-install]: https://github.com/googleapis/google-auth-library-java/blob/main/README.md#google-auth-library-appengine 1108[appengine-app-identity-service]: https://cloud.google.com/appengine/docs/java/javadoc/com/google/appengine/api/appidentity/AppIdentityService 1109[apiary-clients]: https://search.maven.org/search?q=g:com.google.apis 1110[http-credentials-adapter]: https://googleapis.dev/java/google-auth-library/latest/index.html?com/google/auth/http/HttpCredentialsAdapter.html 1111[http-request-initializer]: https://googleapis.dev/java/google-http-client/latest/index.html?com/google/api/client/http/HttpRequestInitializer.html 1112[token-verifier]: https://googleapis.dev/java/google-auth-library/latest/index.html?com/google/auth/oauth2/TokenVerifier.html 1113[token-verifier-builder]: https://googleapis.dev/java/google-auth-library/latest/index.html?com/google/auth/oauth2/TokenVerifier.Builder.html 1114[http-transport-factory]: https://googleapis.dev/java/google-auth-library/latest/index.html?com/google/auth/http/HttpTransportFactory.html 1115[google-credentials]: https://googleapis.dev/java/google-auth-library/latest/index.html?com/google/auth/oauth2/GoogleCredentials.html 1116