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)

FAQs

Get an ID token  |  Authentication  |  Google Cloud? ›

To get an ID token , you need to request them when authenticating users. Auth0 makes it easy for your app to authenticate users using: Quickstarts: The easiest way to implement authentication, which can show you how to use Universal Login, the Lock widget, and Auth0's language and framework-specific SDKs.

How to generate an ID token? ›

To get an ID token , you need to request them when authenticating users. Auth0 makes it easy for your app to authenticate users using: Quickstarts: The easiest way to implement authentication, which can show you how to use Universal Login, the Lock widget, and Auth0's language and framework-specific SDKs.

How do I get the Openid access token? ›

Clients use the token endpoint to exchange the authorization code for an access_token . This token is needed to access the user info endpoint. To request a token, send a HTTP POST request to the /api/openid_connect/token endpoint.

How do I get a cloud ID? ›

If you're a Google Workspace customer
  1. Sign in to your Google Admin console. Sign in using your administrator account (does not end in @gmail.com).
  2. In the Admin console, go to Menu Billing. Get more services.
  3. Click Cloud Identity.
  4. Next to Cloud Identity Premium, click Start Free Trial.
  5. Follow the guided instructions.

How do I get a user token? ›

Get Access Tokens
  1. To request an access token , make a POST call to the token URL.
  2. When a user authenticates, you request an access token and include the target audience and scope of access in your request. ...
  3. In only one specific instance, access tokens can have multiple target audiences.

Where can I get ID token? ›

Get an ID token from the metadata server. When your code is running on a resource that can have a service account attached to it, the metadata server for the associated service can usually provide an ID token.

What is the difference between access token and ID token? ›

They can both be encoded as JWT, but the content and purpose are also different. An ID token contains the identity information about the authenticated users, and it is intended to be consumed by the front-end application. On the other hand, an access token represents a ticket with permission to consume an API.

How can I generate authorization token? ›

If you will use an API key for authentication:
  1. Open secret. ...
  2. Paste it in the field provided.
  3. Provide the required sample Parameters requested.
  4. Click Generate to produce a corresponding Token.io web app URL.
  5. Click Test to link to the Token.io web app and see the UI that will be presented to a customer.

What is ID token in OpenID? ›

The ID token is a security token that includes claims regarding the authentication of the user by the authorization server with the use of an OAuth client application. The ID token may also include other requested claims. It is created on the authorization server's side to encode the user's authentication information.

How do I create a new cloud ID? ›

Tap the sign-in button. Tap Create New Apple ID. Follow the on-screen instructions to set your password, date of birth, region, phone number, payment method, and iCloud email address. Verify your email address using the confirmation email sent to your inbox.

How can I find my cloud ID? ›

Open the Administrator portal. Select Region management. Select Properties and copy the Stamp Cloud ID.

What is a cloud ID number? ›

Cloud/Site/Device ID are specific number found in the URL after login into your cloud. For example, following URL “https://cloud.ignitenet.com/cloud/7323/dashboard” shows that the cloud ID is 7323.

How to get an OAuth token? ›

Steps to Generate OAuth Token
  1. Step 1: Registering a Client.
  2. Step 2: Making the Authorization Request.
  3. Step 3: Generating Tokens.
  4. Step 4: Refreshing your Access Tokens.

What is user ID token? ›

ID tokens are a type of security token that serves as proof of authentication, confirming that a user is successfully authenticated. Information in ID tokens enables the client to verify that a user is who they claim to be, similar to name tags at a conference.

How to get a token code? ›

How to Generate Token Code for Online Transactions
  1. Dial *737*7# with the phone number that is attached to your GTBank account.
  2. Enter your bank account number.
  3. Now, key in the last 6 digits of your GTBank MasterCard.
Mar 12, 2019

How do I create a transfer token ID? ›

Generate a transfer token

Sign in to your Google Admin console. Sign in using an account with super administrator privileges (does not end in @gmail.com). Go to Retrieve Transfer Token. Enter the identifier you got from your reseller, and then click Confirm Reseller Identifier.

What should an ID token contain? ›

An ID token contains information about what happened when a user authenticated, and is intended to be read by the OAuth client. The ID token may also contain information about the user such as their name or email address, although that is not a requirement of an ID token.

How do I create a personal token? ›

In the upper-right corner of any page on GitHub, click your profile photo, then click Settings. In the left sidebar, click Developer settings. In the left sidebar, under Personal access tokens, click Tokens (classic). Select Generate new token, then click Generate new token (classic).

Top Articles
Filing from Outside the US | The Weiss Law Group
C Programming/string.h/strcmp - Wikibooks, open books for an open world
Data reveals most expensive dog breeds in U.S. for 2024 
Pikes Suwanee
Fbsm St Louis
World War II: Summary, Combatants & Facts | HISTORY
Christine Paduch Howell Nj
Pjstar Obits Legacy
Cadenheads Girvan 33yo & Cadenheads Ardmore 11yo
Indianapolis Star Obituary
Craigslist Pet Phoenix
Argus911
Welcome To Aces Charting
Ilcc Number Lookup
Die eID-Karte für Bürgerinnen und Bürger der EU und des EWR
Michelle_Barbelle
Snohomish Hairmasters
Shadow Under The Mountain Skyrim
Oviedo Anonib
Southern Food Buffet Near Me
Netherlands Toys, Games & Hobbies | ExpatINFO Holland
Eos Fitness Irvine
Battle for Azeroth Preview: Drustvar Visitor’s Guide - WoW
Sevierville, Tennessee: Idyllisches Reiseziel in den Great Smoky Mountains
Will Certifier Crossword Clue
Pge Outage Map Beaverton
Reahub 1 Twitter
Berklee College Of Music Academic Calendar
Forza Horizon 5: 8 Best Cars For Rally Racing
Dynasty League Forum
Volkswagen For Sale Craigslist
Panty Note 33
Brake Masters 228
Craigslist Pets Seattle Tacoma Washington
Mathsspot.com Unblocked Roblox Online Unblocked
Craigslist Ct Apartments For Rent
Rinehart Sons Funeral Home
Restaurants Near 275 Tremont St Boston
R/Sandiego
Shop e.chi, Energie Welle, Energie Sohle, E-Smog Kissen, Hologramm
Sparkle Nails Phillipsburg
Lily Starfire White Christmas
Tj Nails Victoria Tx
Sarah Colman-Livengood Park Raytown Photos
Huntington Bank Review 2024 | Bankrate
Sierra At Tahoe Season Pass Costco
Norwegian Luna | Cruise Ship
Gun Show Deridder La
24 Hour Arrest List Knox County
Nuefliks.com
What Is Opm1 Treas 310 Deposit
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.