Programmatic authentication Stay organized with collections Save and categorize content based on your preferences.
This document describes how to authenticate to an IAP-securedresource from a user account or a service account.
Programmatic access refers to calling IAP-secured applicationsfrom non-browser clients, such as command-line tools, service-to-service calls,and mobile applications. Depending on your use case, you might want toauthenticate to IAP using user credentials or service credentials.
Auser account belongs to an individual user. You authenticate a useraccount when your application requires access toIAP-secured resources on a user's behalf. For moreinformation, seeUser accounts.
Caution: Only Google Identities are supported for user account programmaticaccess in IAP. Identity Platform andWorkforce Identity Federation identities are not supported forprogrammatic access.Aservice account represents an application instead of anindividual user. You authenticate a service account when you want to allowan application to access your IAP-secured resources. Formore information, seeService accounts.
IAP supports the following types of credentials for programmaticaccess:
- OAuth 2.0 ID token - A Google-issued token for a human user or serviceaccount with the audience claim set to the resource ID of theIAP application.
- Service account signed JWT - A self-signed or Google-issued JWT tokenfor a service account.
Include these credentials to IAP in theAuthorization orProxy-Authorization HTTP header of the request.
Before you begin
Before you begin, ensure you have an IAP-secured application thatyou want to programmatically connect using a developer account, serviceaccount, or mobile app credentials.
Warning: If you configured your application to use the Google-managed OAuth 2.0 client, programmatic access is blocked by default. You need to add the OAuth 2.0 client to anallowlist so that the callers will use the client to generate credentials.Authenticate a user account
You can enable user access to your application from a desktop or mobile app toallow a program to interact with an IAP-secured resource.
Authenticate from a mobile app
- Create or use an existing OAuth 2.0client ID for your mobile app. To use an existing OAuth 2.0 client ID,follow the steps inHow to share OAuth Clients.Add the OAuth client ID to the allowlist forprogrammatic accessto the application.
- Get an ID token for the OAuth 2.0 client ID of theIAP-secured resource.
- Android: Use theGoogle Sign-In APIto request anOpenID Connect(OIDC) token. Set the
requestIdTokenclient IDto the client ID for the resource you're connecting to. - iOS: UseGoogle Sign-Into get an ID token.
- Android: Use theGoogle Sign-In APIto request anOpenID Connect(OIDC) token. Set the
- Include the ID token in an
Authorization: Bearerheader to make theauthenticated request to the IAP-secured resource.
Authenticate from a desktop app
This section describes how to authenticate a user account from a desktop commandline.
- To allow developers to access your application from the command line,create a desktop OAuth 2.0 client ID orshare an existing desktop OAuth client ID.
- Add the OAuth ID to the allowlist forprogrammatic accessfor the application.
Sign in to the application
Each developer must sign in to access an IAP-secured app. You canpackage the process into a script, such as by usinggcloud CLI. The following example uses curl to signin and generate a token that can be used to access the application:
- Sign in to your account that has access to the Google Cloud resource.
Start a local server that can echo the incoming requests.
# Example using Netcat (http://netcat.sourceforge.net/)nc-k-l4444Go to the following URI, where
DESKTOP_CLIENT_IDis theDesktopapp client ID:https://accounts.google.com/o/oauth2/v2/auth?client_id=DESKTOP_CLIENT_ID&response_type=code&scope=openid%20email&access_type=offline&redirect_uri=http://localhost:4444&cred_ref=trueIn the local server output, look for the request parameters:
GET /?code=CODE&scope=email%20openid%20https://www.googleapis.com/auth/userinfo.email&hd=google.com&prompt=consent HTTP/1.1Copy theCODE value to replaceCODE in the following command, along with theDesktop app client ID and secret:
curl--verbose\--dataclient_id=DESKTOP_CLIENT_ID\--dataclient_secret=DESKTOP_CLIENT_SECRET\--datacode=CODE\--dataredirect_uri=http://localhost:4444\--datagrant_type=authorization_code\https://oauth2.googleapis.com/tokenThis command returns a JSON object with an
id_tokenfield that you can useto access the application.
Access the application
To access the app, use theid_token:
curl--verbose--header'Authorization: BearerID_TOKEN'URLRefresh token
You can use the refresh token generated during the sign-in flow to get new IDtokens. This is useful when the original ID token expires. Each ID token isvalid for about one hour, during which time you can make multiple requests to aspecific app.
The following example uses curl to use the refresh token to get a new ID token.In this example,REFRESH_TOKEN is the token from the sign-in flow.DESKTOP_CLIENT_ID andDESKTOP_CLIENT_SECRET are the same as used in thesign-in flow:
curl--verbose\--dataclient_id=DESKTOP_CLIENT_ID\--dataclient_secret=DESKTOP_CLIENT_SECRET\--datarefresh_token=REFRESH_TOKEN\--datagrant_type=refresh_token\https://oauth2.googleapis.com/tokenThis command returns a JSON object with a newid_token field thatyou can use to access the app.
Authenticate a service account
You can use aservice account JWTor anOpenID Connect(OIDC) token to authenticate a service account with anIAP-secured resource. The following table outlines some of thedifferences between the different authentication tokens and their features.
| Authentication features | Service account JWT | OpenID Connect token |
|---|---|---|
| Context-aware access support | ||
| OAuth 2.0 Client ID requirement | ||
| Token scope | URL of IAP-secured resource | OAuth 2.0 client ID |
Authenticate with a service account JWT
IAP supports service account JWT authentication for Googleidentities, Identity Platform, and Workforce Identity Federation configuredapplications.
Authenticating a service account using a JWT involves the following steps:
Grant the calling service account theService Account Token Creatorrole (
Warning: To follow the principle of least privilege, we recommend that yougrant theroles/iam.serviceAccountTokenCreator).roles/iam.serviceAccountTokenCreatorrole on a specific targetservice account resource and not at the project level. Grantingroles/iam.serviceAccountTokenCreatorat the project level allows theprincipal (the calling service account) to create tokens for any serviceaccount within that project.The role gives principals permission to createshort-lived credentials,like JWTs.
Create a JWT for the IAP-secured resource.
Sign the JWT using the service account private key.
Create the JWT
The created JWT should have a payload similar to the following example:
{"iss":SERVICE_ACCOUNT_EMAIL_ADDRESS,"sub":SERVICE_ACCOUNT_EMAIL_ADDRESS,"aud":TARGET_URL,"iat":IAT,"exp":EXP,}For the
issandsubfields, specify the serviceaccount's email address. The email address is in theclient_emailfield ofthe service account JSON file or is provided as input. Typical format:service-account@PROJECT_ID.iam.gserviceaccount.comFor the
audfield, specify the exact URL or the URL with a path wildcard(/*) of the IAP-secured resource—for example,https://example.com/orhttps://example.com/*. A JWT with the exact URL intheaudfield can only access that specific URL. A JWT with the path wildcard(/*) in theaudfield can access all of the URLs that are prefixed with theaudstring without the trailing*.For the
iatfield, specify the current Unix epoch time, and for theexpfield, specify a time within 3600 seconds later. This defines when the JWTexpires.
Sign the JWT
You can use one of the following methods to sign the JWT:
- Use the IAM credentials API to sign a JWT without requiringdirect access to a private key.
- Use a local credentials key file to sign the JWT locally.
Sign the JWT using IAM Service Account Credentials API
Use the IAM Service Account Credentials API tosign a service account JWT.The method fetches the private key associated with your service account and usesit to sign the JWT payload. This allows the signing of a JWT without directaccess to a private key.
To authenticate to IAP, set up application defaultcredentials. For more information, seeSet up authentication for a local development environment.
gcloud
- Run the following command to prepare a request with the JWT payload:
cat >claim.json <<EOM{"iss":"SERVICE_ACCOUNT_EMAIL_ADDRESS","sub":"SERVICE_ACCOUNT_EMAIL_ADDRESS","aud":"TARGET_URL","iat":$(date+%s),"exp":$((`date+%s`+3600))}EOM- Use the following Google Cloud CLI command to sign the payload in
claim.json:
gcloudiamservice-accountssign-jwt--iam-account="SERVICE_ACCOUNT_EMAIL_ADDRESS"claim.jsonoutput.jwtAfter a successful request,output.jwt contains a signed JWT that you canuse to access your IAP-secured resource.
Python
importdatetimeimportjsonimportgoogle.authfromgoogle.cloudimportiam_credentials_v1defgenerate_jwt_payload(service_account_email:str,resource_url:str)->str:"""Generates JWT payload for service account. Creates a properly formatted JWT payload with standard claims (iss, sub, aud, iat, exp) needed for IAP authentication. Args: service_account_email (str): Specifies the service account that the JWT is created for. resource_url (str): Specifies the scope of the JWT, the URL that the JWT will be allowed to access. Returns: str: JSON string containing the JWT payload with properly formatted claims. """# Create current time and expiration time (1 hour later) in UTCiat=datetime.datetime.now(tz=datetime.timezone.utc)exp=iat+datetime.timedelta(seconds=3600)# Convert datetime objects to numeric timestamps (seconds since epoch)# as required by JWT standard (RFC 7519)payload={"iss":service_account_email,"sub":service_account_email,"aud":resource_url,"iat":int(iat.timestamp()),"exp":int(exp.timestamp()),}returnjson.dumps(payload)defsign_jwt(target_sa:str,resource_url:str)->str:"""Signs JWT payload using ADC and IAM credentials API. Uses Google Cloud's IAM Credentials API to sign a JWT. This requires the caller to have iap.webServiceVersions.accessViaIap permission on the target service account. Args: target_sa (str): Service Account JWT is being created for. iap.webServiceVersions.accessViaIap permission is required. resource_url (str): Audience of the JWT and scope of the JWT token. This is the URL of the IAP-secured application. Returns: str: A signed JWT that can be used to access IAP-secured applications. Use in Authorization header as: 'Bearer <signed_jwt>' """# Get default credentials from environment or application credentialssource_credentials,project_id=google.auth.default()# Initialize IAM credentials client with source credentialsiam_client=iam_credentials_v1.IAMCredentialsClient(credentials=source_credentials)# Generate the service account resource name.# Project should always be "-".# Replacing the wildcard character with a project ID is invalid.name=iam_client.service_account_path("-",target_sa)# Create and sign the JWT payloadpayload=generate_jwt_payload(target_sa,resource_url)# Sign the JWT using the IAM credentials APIresponse=iam_client.sign_jwt(name=name,payload=payload)returnresponse.signed_jwtcurl
Run the following command to prepare a request with the JWT payload:
cat <<EOF >request.json{"payload":JWT_PAYLOAD}EOFSign the JWT using the IAM
Service Account Credentials API:
curl-XPOST\-H"Authorization: Bearer$(gcloudauthprint-access-token)"\-H"Content-Type: application/json; charset=utf-8"\-d@request.json\"https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/SERVICE_ACCOUNT_EMAIL_ADDRESS:signJwt"After a successful request, a signed JWT is returned in the response.
Use the JWT to access your IAP-secured resource.
Sign the JWT from a local credential key file
JWTs are signed using the private key of the service account.
If you have aservice account key file,the JWT can be signed locally.
When signing the JWT locally, include a JWT header with the payload. Forthekid field in the header, use the service account's private key ID, whichis in theprivate_key_id field of the service account credential JSON file.The private key from the file is used to sign the JWT.
Access the application
To access the application, include the signed JWT in the Authorization header:
curl--verbose--header'Authorization: BearerSIGNED_JWT'URLAuthenticate with a service account OIDC token
- Create or use an existing OAuth 2.0client ID. To use an existing OAuth 2.0 client ID, follow the steps inHow to share OAuth Clients.
- Add the OAuth ID to the allowlist forprogrammatic accessfor the application.
- Ensure that the default service account is added to theaccess list for the IAP-secured project.
When making requests to the IAP-secured resource, you mustinclude the token in theAuthorization header:Authorization: 'BearerOIDC_TOKEN'
email claim for IAPto accept it.The following code samples demonstrate how to obtain an OIDC token.
Obtain an OIDC token for the default service account
To get an OIDC token for the default service account forCompute Engine, App Engine, or Cloud Run, reference the followingcode sample to generate a token to access an IAP-securedresource:
C#
To authenticate to IAP, set up Application Default Credentials.For more information, seeSet up authentication for a local development environment.
usingGoogle.Apis.Auth.OAuth2;usingSystem.Net.Http;usingSystem.Net.Http.Headers;usingSystem.Threading;usingSystem.Threading.Tasks;publicclassIAPClient{/// <summary>/// Makes a request to a IAP secured application by first obtaining/// an OIDC token./// </summary>/// <param name="iapClientId">The client ID observed on/// https://console.cloud.google.com/apis/credentials. </param>/// <param name="uri">HTTP URI to fetch.</param>/// <param name="cancellationToken">The token to propagate operation cancel notifications.</param>/// <returns>The HTTP response message.</returns>publicasyncTask<HttpResponseMessage>InvokeRequestAsync(stringiapClientId,stringuri,CancellationTokencancellationToken=default){// Get the OidcToken.// You only need to do this once in your application// as long as you can keep a reference to the returned OidcToken.OidcTokenoidcToken=awaitGetOidcTokenAsync(iapClientId,cancellationToken);// Before making an HTTP request, always obtain the string token from the OIDC token,// the OIDC token will refresh the string token if it expires.stringtoken=awaitoidcToken.GetAccessTokenAsync(cancellationToken);// Include the OIDC token in an Authorization: Bearer header to// IAP-secured resource// Note: Normally you would use an HttpClientFactory to build the httpClient.// For simplicity we are building the HttpClient directly.usingHttpClienthttpClient=newHttpClient();httpClient.DefaultRequestHeaders.Authorization=newAuthenticationHeaderValue("Bearer",token);returnawaithttpClient.GetAsync(uri,cancellationToken);}/// <summary>/// Obtains an OIDC token for authentication an IAP request./// </summary>/// <param name="iapClientId">The client ID observed on/// https://console.cloud.google.com/apis/credentials. </param>/// <param name="cancellationToken">The token to propagate operation cancel notifications.</param>/// <returns>The HTTP response message.</returns>publicasyncTask<OidcToken>GetOidcTokenAsync(stringiapClientId,CancellationTokencancellationToken){// Obtain the application default credentials.GoogleCredentialcredential=awaitGoogleCredential.GetApplicationDefaultAsync(cancellationToken);// Request an OIDC token for the Cloud IAP-secured client ID.returnawaitcredential.GetOidcTokenAsync(OidcTokenOptions.FromTargetAudience(iapClientId),cancellationToken);}}Go
To authenticate to IAP, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
import("context""fmt""io""net/http""google.golang.org/api/idtoken")// makeIAPRequest makes a request to an application protected by Identity-Aware// Proxy with the given audience.funcmakeIAPRequest(wio.Writer,request*http.Request,audiencestring)error{// request, err := http.NewRequest("GET", "http://example.com", nil)// audience := "IAP_CLIENT_ID.apps.googleusercontent.com"ctx:=context.Background()// client is a http.Client that automatically adds an "Authorization" header// to any requests made.client,err:=idtoken.NewClient(ctx,audience)iferr!=nil{returnfmt.Errorf("idtoken.NewClient: %w",err)}response,err:=client.Do(request)iferr!=nil{returnfmt.Errorf("client.Do: %w",err)}deferresponse.Body.Close()if_,err:=io.Copy(w,response.Body);err!=nil{returnfmt.Errorf("io.Copy: %w",err)}returnnil}Java
To authenticate to IAP, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
importcom.google.api.client.http.HttpRequest;importcom.google.api.client.http.HttpRequestInitializer;importcom.google.api.client.http.HttpTransport;importcom.google.api.client.http.javanet.NetHttpTransport;importcom.google.auth.http.HttpCredentialsAdapter;importcom.google.auth.oauth2.GoogleCredentials;importcom.google.auth.oauth2.IdTokenCredentials;importcom.google.auth.oauth2.IdTokenProvider;importcom.google.common.base.Preconditions;importjava.io.IOException;importjava.util.Collections;publicclassBuildIapRequest{privatestaticfinalStringIAM_SCOPE="https://www.googleapis.com/auth/iam";privatestaticfinalHttpTransporthttpTransport=newNetHttpTransport();privateBuildIapRequest(){}privatestaticIdTokenProvidergetIdTokenProvider()throwsIOException{GoogleCredentialscredentials=GoogleCredentials.getApplicationDefault().createScoped(Collections.singleton(IAM_SCOPE));Preconditions.checkNotNull(credentials,"Expected to load credentials");Preconditions.checkState(credentialsinstanceofIdTokenProvider,String.format("Expected credentials that can provide id tokens, got %s instead",credentials.getClass().getName()));return(IdTokenProvider)credentials;}/** * Clone request and add an IAP Bearer Authorization header with ID Token. * * @param request Request to add authorization header * @param iapClientId OAuth 2.0 client ID for IAP protected resource * @return Clone of request with Bearer style authorization header with ID Token. * @throws IOException exception creating ID Token */publicstaticHttpRequestbuildIapRequest(HttpRequestrequest,StringiapClientId)throwsIOException{IdTokenProvideridTokenProvider=getIdTokenProvider();IdTokenCredentialscredentials=IdTokenCredentials.newBuilder().setIdTokenProvider(idTokenProvider).setTargetAudience(iapClientId).build();HttpRequestInitializerhttpRequestInitializer=newHttpCredentialsAdapter(credentials);returnhttpTransport.createRequestFactory(httpRequestInitializer).buildRequest(request.getRequestMethod(),request.getUrl(),request.getContent());}}Node.js
To authenticate to IAP, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
/** * TODO(developer): Uncomment these variables before running the sample. */// const url = 'https://some.iap.url';// const targetAudience = 'IAP_CLIENT_ID.apps.googleusercontent.com';const{GoogleAuth}=require('google-auth-library');constauth=newGoogleAuth();asyncfunctionrequest(){console.info(`request IAP${url} with target audience${targetAudience}`);constclient=awaitauth.getIdTokenClient(targetAudience);constres=awaitclient.fetch(url);console.info(res.data);}request().catch(err=>{console.error(err.message);process.exitCode=1;});PHP
To authenticate to IAP, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
namespace Google\Cloud\Samples\Iap;# Imports Auth libraries and Guzzle HTTP libraries.use Google\Auth\ApplicationDefaultCredentials;use GuzzleHttp\Client;use GuzzleHttp\HandlerStack;/** * Make a request to an application protected by Identity-Aware Proxy. * * @param string $url The Identity-Aware Proxy-protected URL to fetch. * @param string $clientId The client ID used by Identity-Aware Proxy. */function make_iap_request($url, $clientId){ // create middleware, using the client ID as the target audience for IAP $middleware = ApplicationDefaultCredentials::getIdTokenMiddleware($clientId); $stack = HandlerStack::create(); $stack->push($middleware); // create the HTTP client $client = new Client([ 'handler' => $stack, 'auth' => 'google_auth' ]); // make the request $response = $client->get($url); print('Printing out response body:'); print($response->getBody());}Python
To authenticate to IAP, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
fromgoogle.auth.transport.requestsimportRequestfromgoogle.oauth2importid_tokenimportrequestsdefmake_iap_request(url,client_id,method="GET",**kwargs):"""Makes a request to an application protected by Identity-Aware Proxy. Args: url: The Identity-Aware Proxy-protected URL to fetch. client_id: The client ID used by Identity-Aware Proxy. method: The request method to use ('GET', 'OPTIONS', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE') **kwargs: Any of the parameters defined for the request function: https://github.com/requests/requests/blob/master/requests/api.py If no timeout is provided, it is set to 90 by default. Returns: The page body, or raises an exception if the page couldn't be retrieved. """# Set the default timeout, if missingif"timeout"notinkwargs:kwargs["timeout"]=90# Obtain an OpenID Connect (OIDC) token from metadata server or using service# account.open_id_connect_token=id_token.fetch_id_token(Request(),client_id)# Fetch the Identity-Aware Proxy-protected URL, including an# Authorization header containing "Bearer " followed by a# Google-issued OpenID Connect token for the service account.resp=requests.request(method,url,headers={"Authorization":"Bearer{}".format(open_id_connect_token)},**kwargs)ifresp.status_code==403:raiseException("Service account does not have permission to ""access the IAP-protected application.")elifresp.status_code!=200:raiseException("Bad response from application:{!r} /{!r} /{!r}".format(resp.status_code,resp.headers,resp.text))else:returnresp.textRuby
To authenticate to IAP, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
# url = "The Identity-Aware Proxy-protected URL to fetch"# client_id = "The client ID used by Identity-Aware Proxy"require"googleauth"require"faraday"# The client ID as the target audience for IAPid_token_creds=Google::Auth::Credentials.defaulttarget_audience:client_idheaders={}id_token_creds.client.apply!headersresp=Faraday.geturl,nil,headersifresp.status==200puts"X-Goog-Iap-Jwt-Assertion:"putsresp.bodyelseputs"Error requesting IAP"putsresp.statusputsresp.headersendObtain an OIDC token from a local service account key file
To generate an OIDC token using a service account key file, create and sign aJWT assertion using the key file and then exchange that assertion for an IDtoken. The following Bash script demonstrates this process:
Bash
#!/usr/bin/env bash## Example script that generates an OIDC token using a service account key file and uses it to access an IAP-secured resource.set-euopipefailget_token(){# Get the bearer token in exchange for the service account credentialslocalservice_account_key_file_path="${1}"localiap_client_id="${2}"# Define the scope and token endpointlocaliam_scope="https://www.googleapis.com/auth/iam"localoauth_token_uri="https://www.googleapis.com/oauth2/v4/token"# Extract data from service account key filelocalprivate_key_id="$(cat"${service_account_key_file_path}"|jq-r'.private_key_id')"localclient_email="$(cat"${service_account_key_file_path}"|jq-r'.client_email')"localprivate_key="$(cat"${service_account_key_file_path}"|jq-r'.private_key')"# Set token timestamps (current time and expiration 10 minutes later)localissued_at="$(date+%s)"localexpires_at="$((issued_at+600))"# Create JWT header and payloadlocalheader="{'alg':'RS256','typ':'JWT','kid':'${private_key_id}'}"localheader_base64="$(echo"${header}"|base64|tr-d'\n')"localpayload="{'iss':'${client_email}','aud':'${oauth_token_uri}','exp':${expires_at},'iat':${issued_at},'sub':'${client_email}','target_audience':'${iap_client_id}'}"localpayload_base64="$(echo"${payload}"|base64|tr-d'\n')"# Create JWT signature using the private keylocalsignature_base64="$(printf%s"${header_base64}.${payload_base64}"|openssldgst-binary-sha256-sign<(printf'%s\n'"${private_key}") | base64 | tr -d '\n')"localassertion="${header_base64}.${payload_base64}.${signature_base64}"# Exchange the signed JWT assertion for an ID tokenlocaltoken_payload="$(curl-s\--data-urlencode"grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer"\--data-urlencode"assertion=${assertion}"\https://www.googleapis.com/oauth2/v4/token)"# Extract just the ID token from the responselocalbearer_id_token="$(echo"${token_payload}"|jq-r'.id_token')"echo"${bearer_id_token}"}main(){# Check if required arguments are providedif[[$#-lt3]];thenecho"Usage:$0 <service_account_key_file.json> <iap_client_id> <url>"exit1fi# Assign parameters to variablesSERVICE_ACCOUNT_KEY="$1"IAP_CLIENT_ID="$2"URL="$3"# Generate the ID tokenecho"Generating token..."ID_TOKEN=$(get_token"${SERVICE_ACCOUNT_KEY}""${IAP_CLIENT_ID}")# Access the IAP-secured resource with the tokenecho"Accessing:${URL}"curl--header"Authorization: Bearer${ID_TOKEN}""${URL}"}# Run the main function with all provided argumentsmain"$@"This script performs the following steps:
- Extracts the service account key information from your JSON key file
- Creates a JWT with the necessary fields, including the IAPclient ID as the target audience
- Signs the JWT using the service account's private key
- Exchanges this JWT for an OIDC token through Google's OAuth service
- Uses the resulting token to make an authenticated request to yourIAP-secured resource
To use this script:
- Save it to a file, for example:
get_iap_token.sh - Make it executable:
chmod +x get_iap_token.sh - Run it with three parameters:
./get_iap_token.shservice-account-key.json\OAUTH_CLIENT_ID\URLWhere:
service-account-key.jsonis your downloaded service account key file- OAUTH_CLIENT_ID is the OAuth client ID for yourIAP-secured resource
- URL is the URL you want to access
Obtain an OIDC token by using service account impersonation
In all other cases, use the IAM credentials API togenerate an OIDC token byimpersonating a target service account right before accessing anIAP-secured resource. This process involves the followingsteps:
Provide the calling service account (the service account associated with thecode that is obtaining the ID token) with the Service Account OpenID ConnectIdentity Token Creator role (
roles/iam.serviceAccountOpenIdTokenCreator).This gives the calling service account the ability to impersonate the targetservice account.
Use the credentials provided by the calling service account to call thegenerateIdTokenmethod on the target service account.
Set the
audiencefield to your client ID.
For step-by-step instructions, seeCreate an ID token.
Authenticate from Proxy-Authorization Header
If your application uses theAuthorization request header, you can include theID token in aProxy-Authorization: Bearer header instead. If a valid ID tokenis found in aProxy-Authorization header, IAP authorizesthe request with it. After authorizing the request, IAPpasses theAuthorization header to your application without processing thecontent.
If no valid ID token is found in theProxy-Authorization header,IAP continues to process theAuthorization header andstrips theProxy-Authorization header before passing the request to yourapplication.
What's next
- Learn more aboutAuthorization: Bearer Tokens.
- TrySign-In for AndroidorSign-In for iOS.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-02-18 UTC.