Autenticazione programmatica

Questa pagina descrive come eseguire l'autenticazione in una risorsa protetta da Identity-Aware Proxy (IAP) da un account utente o da un account di servizio.

L'accesso programmatico è lo scenario in cui chiami applicazioni protette da IAP da client non browser. Sono inclusi gli strumenti a riga di comando, le chiamate di servizio e le applicazioni mobile. A seconda del caso d'uso, potresti dover eseguire l'autenticazione in IAP utilizzando le credenziali utente o quelle del servizio.

  • Un account utente appartiene a un singolo utente. Autentichi un account utente quando la tua applicazione richiede l'accesso alle risorse protette da IAP per conto di un utente. Per ulteriori informazioni, consulta Account utente.

  • Un account di servizio rappresenta un'applicazione anziché un singolo utente. Autentichi un account di servizio quando vuoi consentire a un'applicazione di accedere alle tue risorse protette da IAP. Per maggiori informazioni, consulta Account di servizio.

IAP supporta i seguenti tipi di credenziali per l'accesso programmatico:

  • Token ID OAuth 2.0: un token emesso da Google per un account di servizio o utente reale con l'affermazione sul pubblico impostata sull'ID risorsa dell'applicazione IAP.
  • JWT firmato dell'account di servizio: un token JWT autofirmato o emesso da Google per un account di servizio.

Passa queste credenziali all'IAP nell'intestazione HTTP Authorization o Proxy-Authorization.

Prima di iniziare

Prima di iniziare, devi avere un'applicazione protetta da acquisti IAP a cui vuoi collegarti tramite programmazione utilizzando un account sviluppatore, un account di servizio o le credenziali di un'app mobile.

Autentica un account utente

Puoi attivare l'accesso degli utenti alla tua app da un'app desktop o mobile per consentire a un programma di interagire con una risorsa protetta da IAP.

Eseguire l'autenticazione da un'app mobile

  1. Crea o utilizza un ID client OAuth 2.0 esistente per la tua app mobile. Per utilizzare un ID client OAuth 2.0 esistente, segui i passaggi descritti in Come condividere i client OAuth. Aggiungi l'ID client OAuth alla lista consentita per l'accesso programmatico dell'applicazione.
  2. Ottieni un token ID per l'ID client protetto da IAP.
  3. Includi il token ID in un'intestazione Authorization: Bearer per effettuare la richiesta autenticata alla risorsa protetta da IAP.

Eseguire l'autenticazione da un'app desktop

Questa sezione descrive come autenticare un account utente da una riga di comando del computer.

  1. Per consentire agli sviluppatori di accedere alla tua applicazione dalla riga di comando, crea un ID client OAuth 2.0 per computer o condividi un ID client OAuth per computer esistente.
  2. Aggiungi l'ID OAuth alla lista consentita per l'accesso programmatico all'applicazione.

Accedi all'applicazione

Ogni sviluppatore che vuole accedere a un'IAP;app protetta da acquisti in-app dovrà prima accedere. Puoi pacchettizzare il processo in uno script, ad esempio utilizzando gcloud CLI. L'esempio seguente utilizza curl per accedere e generare un token che può essere utilizzato per accedere all'applicazione:

  1. Accedi al tuo account che ha accesso alla Google Cloud risorsa.
  2. Avvia un server locale che possa ripetere le richieste in arrivo.

      # Example using Netcat (http://netcat.sourceforge.net/)
      nc -k -l 4444
    
  3. Vai al seguente URI, dove DESKTOP_CLIENT_ID è l'ID client dell'app desktop:

      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=true
    
  4. Nell'output del server locale, cerca i parametri di richiesta:

      GET /?code=CODE&scope=email%20openid%20https://www.googleapis.com/auth/userinfo.email&hd=google.com&prompt=consent HTTP/1.1
    
  5. Copia il valore CODE da sostituire con AUTH_CODE nel comando seguente, insieme all'ID client e al segreto dell'app desktop:

      curl --verbose \
        --data client_id=DESKTOP_CLIENT_ID \
        --data client_secret=DESKTOP_CLIENT_SECRET \
        --data code=CODE \
        --data redirect_uri=http://localhost:4444 \
        --data grant_type=authorization_code \
        https://oauth2.googleapis.com/token
    

    Questo comando restituisce un oggetto JSON con un campo id_token che puoi utilizzare per accedere all'applicazione.

Accedere all'applicazione

Per accedere all'app, utilizza id_token:

curl --verbose --header 'Authorization: Bearer ID_TOKEN' URL

Token di aggiornamento

Puoi utilizzare il token di aggiornamento generato durante il flusso di accesso per ottenere nuovi token identificativi. Questo è utile quando il token ID originale scade. Ogni token ID è valido per circa un'ora, durante la quale puoi effettuare più richieste a un'app specifica.

L'esempio seguente utilizza curl per utilizzare il token di aggiornamento per ottenere un nuovo token ID. In questo esempio, REFRESH_TOKEN è il token del flusso di accesso. DESKTOP_CLIENT_ID e DESKTOP_CLIENT_SECRET sono gli stessi utilizzati nel flusso di accesso:

curl --verbose \
  --data client_id=DESKTOP_CLIENT_ID \
  --data client_secret=DESKTOP_CLIENT_SECRET \
  --data refresh_token=REFRESH_TOKEN \
  --data grant_type=refresh_token \
  https://oauth2.googleapis.com/token

Questo comando restituisce un oggetto JSON con un nuovo campo id_token che puoi utilizzare per accedere all'app.

Autenticare un account di servizio

Puoi utilizzare un token JWT dell'account di servizio o un token OpenID Connect (OIDC) per autenticare un account di servizio con una risorsa protetta da IAP. La tabella seguente illustra alcune delle differenze tra i diversi token di autenticazione e le relative funzionalità.

Funzionalità di autenticazione JWT dell'account di servizio Token OpenID Connect
Supporto dell'accesso sensibile al contesto
Requisito relativo all'ID client OAuth 2.0
Ambito del token URL della risorsa protetta da IAP ID client OAuth 2.0

Eseguire l'autenticazione con un token JWT dell'account di servizio

IAP supporta l'autenticazione JWT dell'account di servizio per le applicazioni configurate di Google Identities, Identity Platform e Workforce Identity Federation.

L'autenticazione di un account di servizio utilizzando un JWT prevede i seguenti passaggi principali:

  1. Concedi all'account di servizio chiamante il ruolo Creatore token account di servizio (roles/iam.serviceAccountTokenCreator).

    Il ruolo concede ai principali l'autorizzazione a creare credenziali di breve durata, come i JWT.

  2. Crea un JWT per la risorsa protetta da IAP.

  3. Firma il JWT utilizzando la chiave privata dell'account di servizio.

Creazione del JWT

Il JWT creato deve avere un payload simile all'esempio seguente:

{
  "iss": SERVICE_ACCOUNT_EMAIL_ADDRESS,
  "sub": SERVICE_ACCOUNT_EMAIL_ADDRESS,
  "aud": TARGET_URL,
  "iat": IAT,
  "exp": EXP,
}
  • Per i campi iss e sub, specifica l'indirizzo email dell'account di servizio. Si trova nel campo client_email del file JSON dell'account di servizio o viene passato. Formato tipico: service-account@PROJECT_ID.iam.gserviceaccount.com

  • Per il campo aud, specifica l'URL della risorsa protetta da IAP.

  • Per il campo iat, specifica l'ora corrente dell'epoca Unix e per il campo exp specifica un'ora successiva a 3600 secondi. Questo definisce la data di scadenza del JWT.

Firma del JWT

Per firmare il JWT, puoi utilizzare uno dei seguenti metodi:

  • Utilizza l'API delle credenziali IAM per firmare un JWT senza richiedere accesso diretto a una chiave privata.
  • Utilizza un file di chiavi delle credenziali locali per firmare il JWT localmente.
Firma del JWT utilizzando l'API IAM Service Account Credentials

Utilizza l'API Credenziali dell'account di servizio IAM per firmare un JWT dell'account di servizio. Il metodo recupera la chiave privata associata al tuo account di servizio e la utilizza per firmare il payload JWT. In questo modo è possibile firmare un JWT senza accesso diretto a una chiave privata.

Per autenticarti a IAP, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

gcloud

  1. Esegui il seguente comando per preparare una richiesta con il payload JWT
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
  1. Utilizza il seguente comando Google Cloud CLI per firmare il payload in claim.json:
gcloud iam service-accounts sign-jwt --iam-account="SERVICE_ACCOUNT_EMAIL_ADDRESS" claim.json output.jwt

Dopo una richiesta andata a buon fine, output.jwt contiene un JWT firmato che puoi utilizzare per accedere alla risorsa protetta da IAP.

Python

import datetime
import json

import google.auth
from google.cloud import iam_credentials_v1

def generate_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 service account JWT is created for.
        resource_url (str): Specifies 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 UTC
    iat = 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()),
    }

    return json.dumps(payload)

def sign_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 protected application.

    Returns:
        str: A signed JWT that can be used to access IAP protected apps.
            Use in Authorization header as: 'Bearer <signed_jwt>'
    """
    # Get default credentials from environment or application credentials
    source_credentials, project_id = google.auth.default()

    # Initialize IAM credentials client with source credentials
    iam_client = iam_credentials_v1.IAMCredentialsClient(credentials=source_credentials)

    # Generate the service account resource name
    # If project_id is None, use '-' as placeholder as per API requirements
    project = project_id if project_id else "-"
    name = iam_client.service_account_path(project, target_sa)

    # Create and sign the JWT payload
    payload = generate_jwt_payload(target_sa, resource_url)

    # Sign the JWT using the IAM credentials API
    response = iam_client.sign_jwt(name=name, payload=payload)

    return response.signed_jwt

curl

  1. Esegui il comando seguente per preparare una richiesta con il payload JWT:

    cat << EOF > request.json
    {
      "payload": JWT_PAYLOAD
    }
    EOF
    
  2. Firma il JWT utilizzando IAM

    API Service Account Credentials:

    curl -X POST \
      -H "Authorization: Bearer $(gcloud auth print-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"
    

    Dopo una richiesta andata a buon fine, nella risposta viene restituito un JWT firmato.

  3. Utilizza il JWT per accedere alla risorsa protetta da IAP.

Firma del JWT da un file della chiave delle credenziali locale

I JWT vengono firmati utilizzando la chiave privata dell'account di servizio.

Se disponi di un file della chiave dell'account di servizio, il JWT può essere firmato localmente.

Lo script invia un'intestazione JWT insieme al payload. Per il campo kid nell'intestazione, utilizza l'ID chiave privata dell'account di servizio, che si trova nel private_key_id campo del file JSON delle credenziali dell'account di servizio. La chiave viene utilizzata anche per firmare il JWT.

Accedere all'applicazione

In tutti i casi, per accedere all'app, usa signed-jwt:

curl --verbose --header 'Authorization: Bearer SIGNED_JWT' URL

Eseguire l'autenticazione con un token OIDC

  1. Crea o utilizza un ID client OAuth 2.0 esistente. Per utilizzare un ID client OAuth 2.0 esistente, segui i passaggi descritti in Come condividere i client OAuth.
  2. Aggiungi l'ID OAuth alla lista consentita per l'accesso programmatico all'applicazione.
  3. Assicurati che l'account di servizio predefinito sia aggiunto all'elenco per gli accessi per il progetto protetto da IAP.

Quando effettui richieste alla risorsa protetta da IAP, devi includere il token nell'intestazione Authorization: Authorization: 'Bearer OIDC_TOKEN'

I seguenti esempi di codice mostrano come ottenere un token OIDC.

Ottenere un token OIDC per l'account di servizio predefinito

Per ottenere un token OIDC per l'account di servizio predefinito per Compute Engine, App Engine o Cloud Run, fai riferimento al seguente esempio di codice per generare un token per accedere a una risorsa protetta da IAP:

C#

Per effettuare l'autenticazione in IAP, configura le credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configurare l'autenticazione per un ambiente di sviluppo locale.


using Google.Apis.Auth.OAuth2;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;

public class IAPClient
{
    /// <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>
    public async Task<HttpResponseMessage> InvokeRequestAsync(
        string iapClientId, string uri, CancellationToken cancellationToken = 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.
        OidcToken oidcToken = await GetOidcTokenAsync(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.
        string token = await oidcToken.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.
        using HttpClient httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        return await httpClient.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>
    public async Task<OidcToken> GetOidcTokenAsync(string iapClientId, CancellationToken cancellationToken)
    {
        // Obtain the application default credentials.
        GoogleCredential credential = await GoogleCredential.GetApplicationDefaultAsync(cancellationToken);

        // Request an OIDC token for the Cloud IAP-secured client ID.
       return await credential.GetOidcTokenAsync(OidcTokenOptions.FromTargetAudience(iapClientId), cancellationToken);
    }
}

Go

Per effettuare l'autenticazione in IAP, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

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.
func makeIAPRequest(w io.Writer, request *http.Request, audience string) 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)
	if err != nil {
		return fmt.Errorf("idtoken.NewClient: %w", err)
	}

	response, err := client.Do(request)
	if err != nil {
		return fmt.Errorf("client.Do: %w", err)
	}
	defer response.Body.Close()
	if _, err := io.Copy(w, response.Body); err != nil {
		return fmt.Errorf("io.Copy: %w", err)
	}

	return nil
}

Java

Per effettuare l'autenticazione in IAP, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.


import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.IdTokenCredentials;
import com.google.auth.oauth2.IdTokenProvider;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.util.Collections;

public class BuildIapRequest {
  private static final String IAM_SCOPE = "https://www.googleapis.com/auth/iam";

  private static final HttpTransport httpTransport = new NetHttpTransport();

  private BuildIapRequest() {}

  private static IdTokenProvider getIdTokenProvider() throws IOException {
    GoogleCredentials credentials =
        GoogleCredentials.getApplicationDefault().createScoped(Collections.singleton(IAM_SCOPE));

    Preconditions.checkNotNull(credentials, "Expected to load credentials");
    Preconditions.checkState(
        credentials instanceof IdTokenProvider,
        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
   */
  public static HttpRequest buildIapRequest(HttpRequest request, String iapClientId)
      throws IOException {

    IdTokenProvider idTokenProvider = getIdTokenProvider();
    IdTokenCredentials credentials =
        IdTokenCredentials.newBuilder()
            .setIdTokenProvider(idTokenProvider)
            .setTargetAudience(iapClientId)
            .build();

    HttpRequestInitializer httpRequestInitializer = new HttpCredentialsAdapter(credentials);

    return httpTransport
        .createRequestFactory(httpRequestInitializer)
        .buildRequest(request.getRequestMethod(), request.getUrl(), request.getContent());
  }
}

Node.js

Per effettuare l'autenticazione in IAP, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

/**
 * 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');
const auth = new GoogleAuth();

async function request() {
  console.info(`request IAP ${url} with target audience ${targetAudience}`);
  const client = await auth.getIdTokenClient(targetAudience);
  const res = await client.fetch(url);
  console.info(res.data);
}

request().catch(err => {
  console.error(err.message);
  process.exitCode = 1;
});

PHP

Per effettuare l'autenticazione in IAP, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

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

Per effettuare l'autenticazione in IAP, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

from google.auth.transport.requests import Request
from google.oauth2 import id_token
import requests


def make_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 missing
    if "timeout" not in kwargs:
        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
    )
    if resp.status_code == 403:
        raise Exception(
            "Service account does not have permission to "
            "access the IAP-protected application."
        )
    elif resp.status_code != 200:
        raise Exception(
            "Bad response from application: {!r} / {!r} / {!r}".format(
                resp.status_code, resp.headers, resp.text
            )
        )
    else:
        return resp.text

Ruby

Per effettuare l'autenticazione in IAP, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

# 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 IAP
id_token_creds = Google::Auth::Credentials.default target_audience: client_id

headers = {}
id_token_creds.client.apply! headers

resp = Faraday.get url, nil, headers

if resp.status == 200
  puts "X-Goog-Iap-Jwt-Assertion:"
  puts resp.body
else
  puts "Error requesting IAP"
  puts resp.status
  puts resp.headers
end

Ottenere un token OIDC da un file della chiave dell'account di servizio locale

Per generare un token OIDC utilizzando un file della chiave dell'account di servizio, dovrai utilizzare il file della chiave per creare e firmare un'affermazione JWT, quindi scambiarla con un token ID. Il seguente script Bash dimostra questa procedura:

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 -euo pipefail

get_token() {
  # Get the bearer token in exchange for the service account credentials
  local service_account_key_file_path="${1}"
  local iap_client_id="${2}"

  # Define the scope and token endpoint
  local iam_scope="https://www.googleapis.com/auth/iam"
  local oauth_token_uri="https://www.googleapis.com/oauth2/v4/token"

  # Extract data from service account key file
  local private_key_id="$(cat "${service_account_key_file_path}" | jq -r '.private_key_id')"
  local client_email="$(cat "${service_account_key_file_path}" | jq -r '.client_email')"
  local private_key="$(cat "${service_account_key_file_path}" | jq -r '.private_key')"

  # Set token timestamps (current time and expiration 10 minutes later)
  local issued_at="$(date +%s)"
  local expires_at="$((issued_at + 600))"

  # Create JWT header and payload
  local header="{'alg':'RS256','typ':'JWT','kid':'${private_key_id}'}"
  local header_base64="$(echo "${header}" | base64 | tr -d '\n')"
  local payload="{'iss':'${client_email}','aud':'${oauth_token_uri}','exp':${expires_at},'iat':${issued_at},'sub':'${client_email}','target_audience':'${iap_client_id}'}"
  local payload_base64="$(echo "${payload}" | base64 | tr -d '\n')"

  # Create JWT signature using the private key
  local signature_base64="$(printf %s "${header_base64}.${payload_base64}" | openssl dgst -binary -sha256 -sign <(printf '%s\n' "${private_key}")  | base64 | tr -d '\n')"
  local assertion="${header_base64}.${payload_base64}.${signature_base64}"

  # Exchange the signed JWT assertion for an ID token
  local token_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 response
  local bearer_id_token="$(echo "${token_payload}" | jq -r '.id_token')"
  echo "${bearer_id_token}"
}

main() {
  # Check if required arguments are provided
  if [[ $# -lt 3 ]]; then
    echo "Usage: $0 <service_account_key_file.json> <iap_client_id> <url>"
    exit 1
  fi

  # Assign parameters to variables
  SERVICE_ACCOUNT_KEY="$1"
  IAP_CLIENT_ID="$2"
  URL="$3"

  # Generate the ID token
  echo "Generating token..."
  ID_TOKEN=$(get_token "${SERVICE_ACCOUNT_KEY}" "${IAP_CLIENT_ID}")

  # Access the IAP-secured resource with the token
  echo "Accessing: ${URL}"
  curl --header "Authorization: Bearer ${ID_TOKEN}" "${URL}"
}

# Run the main function with all provided arguments
main "$@"

Questo script esegue i seguenti passaggi:

  1. Estrae le informazioni sulla chiave dell'account di servizio dal file della chiave JSON
  2. Crea un JWT con i campi necessari, incluso l'ID client IAP come pubblico di destinazione
  3. Firma il JWT utilizzando la chiave privata dell'account di servizio
  4. Scambia questo JWT con un token OIDC tramite il servizio OAuth di Google
  5. Utilizza il token risultante per effettuare una richiesta autenticata alla risorsa protetta da IAP

Per utilizzare questo script:

  1. Salvalo in un file, ad esempio: get_iap_token.sh
  2. Rendilo eseguibile: chmod +x get_iap_token.sh
  3. Eseguilo con tre parametri:
  ./get_iap_token.sh service-account-key.json \
    OAUTH_CLIENT_ID \
    URL

Dove:

  • service-account-key.json è il file della chiave del account di servizio scaricato
  • OAUTH_CLIENT_ID è l'ID client OAuth per la risorsa protetta da acquisti IAP
  • URL è l'URL a cui vuoi accedere

Ottenere un token OIDC in tutti gli altri casi

In tutti gli altri casi, utilizza l'API delle credenziali IAM per generare un token OIDC fingendo di essere un account di servizio di destinazione subito prima di accedere a una risorsa protetta da IAP. Questa procedura prevede i seguenti passaggi:

  1. Fornisci all'account di servizio chiamante (l'account di servizio associato al codice che sta ottenendo il token ID) il ruolo Service Account OpenID Connect Identity Token Creator (roles/iam.serviceAccountOpenIdTokenCreator).

    In questo modo, l'account di servizio chiamante può simulare l'identità dell'account di servizio di destinazione.

  2. Utilizza le credenziali fornite dall'account di servizio chiamante per chiamare il metodo generateIdToken nell'account di servizio di destinazione.

    Imposta il campo audience sul tuo ID client.

Per istruzioni dettagliate, consulta Creare un token ID.

Autentica dall'intestazione Proxy-Authorization

Se la tua applicazione utilizza l'intestazione di richiesta Authorization, puoi includere il token identificativo in un'intestazione Proxy-Authorization: Bearer. Se in un'intestazione Proxy-Authorization viene trovato un token ID valido, IAP autorizza la richiesta. Dopo aver autorizzato la richiesta, IAP trasmette l'intestazione Authorization alla tua applicazione senza elaborare i contenuti.

Se nell'intestazione Proxy-Authorization non viene trovato alcun token ID valido, IAP continua a elaborare l'intestazione Proxy-Authorization e la rimuove prima di passare la richiesta all'applicazione.Authorization

Passaggi successivi