Get an ID token  |  Authentication  |  Google Cloud (2024)

This page describes some ways to acquire a Google-signed OpenID Connect (OIDC)ID token. You need a Google-signed ID token for the following authenticationuse cases:

For information about ID token contents and lifetimes, seeID tokens.

ID tokens have a specific service or application that they can be used for,specified by the value of their aud claim. This page uses theterm target service to refer to the service or application that the ID tokencan be used to authenticate to.

When you get the ID token, you can include it in anAuthorization header in the request to the target service.

Methods for getting an ID token

There are various ways to get an ID token. This page describes the followingmethods:

  • Get an ID token from the metadata server
  • Use a connecting service to generate an ID token
  • Generate an ID token by impersonating a service account
  • Generate a generic ID token for development with Cloud Run and Cloud Functions
  • Generate an ID token using an external identity provider

Cloud Run and Cloud Functions provide service-specific ways toget an ID token. For more information, seeAuthenticate to applications hosted on Cloud Run or Cloud Functions.

If you need an ID token to be accepted by an application not hosted onGoogle Cloud, you can probably use these methods. However, you shoulddetermine what ID token claims the application requires.

Get an ID token from the metadata server

When your code is running on a resource that can have aservice account attached to it,the metadata server for the associated service can usually provide an ID token.The metadata server generates ID tokens for the attached service account. Youcannot get an ID token based on user credentials from the metadata server.

You can get an ID token from the metadata server when your code is runningon the following Google Cloud services:

To retrieve an ID token from the metadata server, you query the identityendpoint for the service account, as shown in this example.

curl

Replace AUDIENCE with the URI for the target service,for example http://www.example.com.

curl -H "Metadata-Flavor: Google" \ 'http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience=AUDIENCE'

PowerShell

Replace AUDIENCE with the URI for the target service,for example http://www.example.com.

$value = (Invoke-RestMethod ` -Headers @{'Metadata-Flavor' = 'Google'} ` -Uri "http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience=AUDIENCE")$value

Java

To run this code sample, you must install theGoogle API Client Library for Java.

import com.google.auth.oauth2.GoogleCredentials;import com.google.auth.oauth2.IdTokenCredentials;import com.google.auth.oauth2.IdTokenProvider;import com.google.auth.oauth2.IdTokenProvider.Option;import java.io.IOException;import java.security.GeneralSecurityException;import java.util.Arrays;public class IdTokenFromMetadataServer { public static void main(String[] args) throws IOException, GeneralSecurityException { // TODO(Developer): Replace the below variables before running the code. // The url or target audience to obtain the ID token for. String url = "https://example.com"; getIdTokenFromMetadataServer(url); } // Use the Google Cloud metadata server to create an identity token and add it to the // HTTP request as part of an Authorization header. public static void getIdTokenFromMetadataServer(String url) throws IOException { // Construct the GoogleCredentials object which obtains the default configuration from your // working environment. GoogleCredentials googleCredentials = GoogleCredentials.getApplicationDefault(); IdTokenCredentials idTokenCredentials = IdTokenCredentials.newBuilder() .setIdTokenProvider((IdTokenProvider) googleCredentials) .setTargetAudience(url) // Setting the ID token options. .setOptions(Arrays.asList(Option.FORMAT_FULL, Option.LICENSES_TRUE)) .build(); // Get the ID token. // Once you've obtained the ID token, you can use it to make an authenticated call to the // target audience. String idToken = idTokenCredentials.refreshAccessToken().getTokenValue(); System.out.println("Generated ID token."); }}

Go

import ("context""fmt""io""golang.org/x/oauth2/google""google.golang.org/api/idtoken""google.golang.org/api/option")// getIdTokenFromMetadataServer uses the Google Cloud metadata server environment// to create an identity token and add it to the HTTP request as part of an Authorization header.func getIdTokenFromMetadataServer(w io.Writer, url string) error {// url := "http://www.example.com"ctx := context.Background()// Construct the GoogleCredentials object which obtains the default configuration from your// working environment.credentials, err := google.FindDefaultCredentials(ctx)if err != nil {return fmt.Errorf("failed to generate default credentials: %w", err)}ts, err := idtoken.NewTokenSource(ctx, url, option.WithCredentials(credentials))if err != nil {return fmt.Errorf("failed to create NewTokenSource: %w", err)}// Get the ID token.// Once you've obtained the ID token, you can use it to make an authenticated call// to the target audience._, err = ts.Token()if err != nil {return fmt.Errorf("failed to receive token: %w", err)}fmt.Fprintf(w, "Generated ID token.\n")return nil}

Node.js

/** * TODO(developer): * 1. Uncomment and replace these variables before running the sample. */// const targetAudience = 'http://www.example.com';const {GoogleAuth} = require('google-auth-library');async function getIdTokenFromMetadataServer() { const googleAuth = new GoogleAuth(); const client = await googleAuth.getIdTokenClient(targetAudience); // Get the ID token. // Once you've obtained the ID token, you can use it to make an authenticated call // to the target audience. await client.idTokenProvider.fetchIdToken(targetAudience); console.log('Generated ID token.');}getIdTokenFromMetadataServer();

Python

To run this code sample, you must install theGoogle Auth Python Library.

import googleimport google.oauth2.credentialsfrom google.auth import compute_engineimport google.auth.transport.requestsdef idtoken_from_metadata_server(url: str): """ Use the Google Cloud metadata server in the Cloud Run (or AppEngine or Kubernetes etc.,) environment to create an identity token and add it to the HTTP request as part of an Authorization header. Args: url: The url or target audience to obtain the ID token for. Examples: http://www.example.com """ request = google.auth.transport.requests.Request() # Set the target audience. # Setting "use_metadata_identity_endpoint" to "True" will make the request use the default application # credentials. Optionally, you can also specify a specific service account to use by mentioning # the service_account_email. credentials = compute_engine.IDTokenCredentials( request=request, target_audience=url, use_metadata_identity_endpoint=True ) # Get the ID token. # Once you've obtained the ID token, use it to make an authenticated call # to the target audience. credentials.refresh(request) # print(credentials.token) print("Generated ID token.")

Ruby

To run this code sample, you must install theGoogle Auth Library for Ruby.

require "googleauth"### Uses the Google Cloud metadata server environment to create an identity token# and add it to the HTTP request as part of an Authorization header.## @param url [String] The url or target audience to obtain the ID token for# (e.g. "http://www.example.com")#def auth_cloud_idtoken_metadata_server url: # Create the GCECredentials client. id_client = Google::Auth::GCECredentials.new target_audience: url # Get the ID token. # Once you've obtained the ID token, you can use it to make an authenticated call # to the target audience. id_client.fetch_access_token puts "Generated ID token." id_client.refresh!end

Use a connecting service to generate an ID token

Some Google Cloud services help you call other services. These connectingservices might help determine when the call gets made, or manage a workflow thatincludes calling the service. The following services can automatically includean ID token, with the appropriate value for the aud claim, when they initiatea call to a service that requires an ID token:

Pub/Sub
Pub/Sub enables asynchronous communication between services.You can configure Pub/Sub to include an ID token with amessage. For more information, seeAuthentication for push subscription.
Cloud Tasks
Cloud Tasks lets you manage the execution of distributedtasks. You can configure a task to include either an ID token or an accesstoken when it calls a service. For more information, seeUsing HTTP Target tasks with authentication tokens.
Cloud Scheduler
Cloud Scheduler is a fully managed enterprise-grade cron jobscheduler. You can configure Cloud Scheduler to include either anID token or an access token when it invokes another service. For moreinformation, seeUsing authentication with HTTP Targets.

Generate an ID token by impersonating a service account

Service account impersonation allows a principal to generate short-livedcredentials for a trusted service account. The principal can then use thesecredentials to authenticate as the service account.

Before a principal can impersonate a service account, it must have anIAM role on that service account that enables impersonation.If the principal is itself another service account, it might seem easier tosimply provide the required permissions directly to that service account, andenable it to impersonate itself. This configuration, known asself-impersonation, creates a security vulnerability, because it lets theservice account create an access token that can be refreshed in perpetuity.

Service account impersonation should always involve twoprincipals: a principal that represents the caller, and the service account thatis being impersonated, called the privilege-bearing service account.

To generate an ID token by impersonating a service account, you use thefollowing general process.

For step-by-step instructions, seeCreate an ID token.

  1. Identify or create a service account to be the privilege-bearingservice account. Grant that service account the required IAMrole, on the target service:

    • For Cloud Run services, grant the Cloud Run Invoker role(roles/run.invoker).
    • For Cloud Functions, grant the Cloud Functions Invoker role(roles/cloudfunctions.invoker).
    • For other target services, see the product documentation for the service.
  2. Identify the principal that will perform the impersonation, and set upApplication Default Credentials (ADC) to use the credentials forthis principal.

    For development environments, the principal is usually the user account youprovided to ADC by using the gcloud CLI. However, if you'rerunning on a resource with a service account attached, the attached serviceaccount is the principal.

  3. Grant the principal the Service Account OpenID Connect Identity Token Creator role (roles/iam.serviceAccountOpenIdTokenCreator).

  4. Use the IAM Credentials API to generatethe ID token for the authorized service account.

Generate a generic ID token for development with Cloud Run and Cloud Functions

You can use the gcloud CLI to get an ID token for your usercredentials that can be used with any Cloud Run service orCloud Function that the caller has the required IAM permissions toinvoke. This token will not work for any other application.

Generate an ID token using an external identity provider

Generating an ID token using an external identity provider usesworkload identity federation, which lets you set up a relationshipbetween Google Cloud and your external identity provider. You can then usecredentials supplied by your external identity provider to generate ID tokens oraccess tokens that can be used in Google Cloud.

To generate an ID token for credentials supplied from an external identityprovider, follow these steps:

  1. Identify or create a service account to provide theIAM roles required to call the target service.

    It's a best practice to create a service account specifically for thispurpose, and provide it with only the required role. This approach followsthe principle of least privilege.

  2. Identify the required roles to invoke the target service. Grant these rolesto the service account on the target service:

    • ForCloud Run services,grant the Cloud Run Invoker role (roles/run.invoker).
    • ForCloud Functions,grant the Cloud Functions Invoker role (roles/cloudfunctions.invoker).
    • For other target services, see the product documentation for the service.
  3. Configure workload identity federation for your identity provider asdescribed in Configuring workload identity federation.

  4. Follow the instructions inGranting external identities permission to impersonate a service account.Use the service account you set up in the previous steps as the serviceaccount to be impersonated.

  5. Use the REST API to acquire a short-lived token, but for thelast step, use thegenerateIdTokenmethod instead, to get an ID token:

    Bash

    ID_TOKEN=$(curl -0 -X POST https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/SERVICE_ACCOUNT_EMAIL:generateIdToken \ -H "Content-Type: text/json; charset=utf-8" \ -H "Authorization: Bearer $STS_TOKEN" \ -d @- <<EOF | jq -r .token { "audience": "AUDIENCE" }EOF)echo $ID_TOKEN

    PowerShell

    $IdToken = (Invoke-RestMethod ` -Method POST ` -Uri "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/SERVICE_ACCOUNT_EMAIL:generateIdToken" ` -Headers @{ "Authorization" = "Bearer $StsToken" } ` -ContentType "application/json" ` -Body (@{ "audience" = "AUDIENCE" } | ConvertTo-Json)).tokenWrite-Host $IdToken

    Replace the following:

    • SERVICE_ACCOUNT_EMAIL: the email address of the service account
    • AUDIENCE: the audience for the token, such as the application or service that the token will be used to access

What's next

As an expert in Google Cloud authentication and identity management, I can confidently guide you through the concepts and methods described in the article about acquiring a Google-signed OpenID Connect (OIDC) ID token. My extensive knowledge in this domain is backed by a deep understanding of the authentication use cases, various methods for obtaining ID tokens, and the specific services involved.

Firstly, let's discuss the key concepts used in the article:

  1. Google-signed OpenID Connect (OIDC) ID Token:

    • This is a token provided by Google for authentication purposes.
    • It is used in various authentication scenarios, such as accessing Cloud Run services, invoking Cloud Functions, authenticating users with Identity-Aware Proxy (IAP), and making requests to APIs deployed with API Gateway or Cloud Endpoints.
  2. Audience (aud) Claim:

    • ID tokens have a specific service or application they can be used for, identified by the "aud" claim.
    • The term "target service" is used to refer to the service or application that the ID token can authenticate.
  3. Methods for Getting an ID Token:

    • The article outlines several methods for obtaining an ID token, including:
      • Getting it from the metadata server when running on Google Cloud services like Compute Engine, App Engine, Cloud Functions, Cloud Run, Google Kubernetes Engine, and Cloud Build.
      • Using connecting services like Pub/Sub, Cloud Tasks, and Cloud Scheduler to automatically include an ID token when making calls to other services.
      • Impersonating a service account to generate a short-lived credential for authentication.
      • Generating a generic ID token for development using the gcloud CLI.
      • Using an external identity provider for workload identity federation.
  4. Code Samples for Getting an ID Token:

    • The article provides code samples in various programming languages (Java, Go, Node.js, Python, and Ruby) to illustrate how to obtain an ID token from the metadata server.
  5. Use of External Identity Providers:

    • The article discusses the process of generating an ID token using an external identity provider through workload identity federation.
    • It outlines steps such as identifying or creating a service account, granting required roles, configuring workload identity federation, and using the REST API to acquire a short-lived token.
  6. Shell Commands for ID Token Generation:

    • Shell commands are provided for generating an ID token using the REST API and an external identity provider.
    • The commands involve making HTTP requests to the IAM Credentials API.
  7. Further Resources:

    • The article suggests further reading on understanding ID tokens, verifying ID tokens, querying the Compute Engine metadata server using shell commands, and learning more about authentication at Google.

In summary, this article comprehensively covers the concepts and methods related to acquiring Google-signed OpenID Connect (OIDC) ID tokens, showcasing a depth of expertise in Google Cloud authentication practices. If you have any specific questions or if there's a particular aspect you'd like more information on, feel free to ask.

Get an ID token  |  Authentication  |  Google Cloud (2024)
Top Articles
Latest Posts
Article information

Author: Domingo Moore

Last Updated:

Views: 6299

Rating: 4.2 / 5 (73 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Domingo Moore

Birthday: 1997-05-20

Address: 6485 Kohler Route, Antonioton, VT 77375-0299

Phone: +3213869077934

Job: Sales Analyst

Hobby: Kayaking, Roller skating, Cabaret, Rugby, Homebrewing, Creative writing, amateur radio

Introduction: My name is Domingo Moore, I am a attractive, gorgeous, funny, jolly, spotless, nice, fantastic person who loves writing and wants to share my knowledge and understanding with you.