Protezione dell'app con intestazioni firmate

In questa pagina viene descritto come proteggere l'app con le intestazioni IAP firmate. Quando è configurato, Identity-Aware Proxy (IAP) utilizza i token web JSON (JWT) per assicurarsi che una richiesta alla tua app sia autorizzata. In questo modo, la tua app è protetta dai seguenti rischi:

  • IAP è disattivato accidentalmente
  • Firewall configurati in modo errato
  • Accesso non autorizzato dall'interno del progetto

Per proteggere l'app, devi utilizzare le intestazioni firmate per tutti i tipi di app.

In alternativa, se hai un'app dell'ambiente standard App Engine, puoi utilizzare l'API Users.

I controlli di integrità di Compute Engine e GKE non includono le intestazioni JWT e IAP non elabora i controlli di integrità. Se il controllo di integrità restituisce errori di accesso, assicurati di aver configurato correttamente il controllo di integrità nellaconsola Google Cloud e che la convalida dell'intestazione JWT consenta il percorso del controllo di integrità. Per saperne di più, consulta Creare un'eccezione del controllo di integrità.

Prima di iniziare

Per proteggere l'app con le intestazioni firmate, avrai bisogno di:

Proteggere l'app con le intestazioni IAP

Per proteggere l'app con il JWT IAP, verifica l'intestazione, il payload e la firma del JWT. Il JWT si trova nell'intestazione della richiesta HTTP x-goog-iap-jwt-assertion. Se un utente malintenzionato bypassa IAP, può falsificare le intestazioni dell'identità non firmate di IAP, x-goog-authenticated-user-{email,id}. Il JWT IAP fornisce un'alternativa più sicura.

Le intestazioni firmate forniscono una sicurezza secondaria nel caso in cui qualcuno bypassi IAP. Quando IAP è abilitato, rimuove le intestazioni x-goog-* fornite dal client quando la richiesta passa attraverso l'infrastruttura di pubblicazione di IAP.

Verificare l'intestazione JWT

Verifica che l'intestazione del JWT sia conforme ai seguenti vincoli:

Rivendicazioni dell'intestazione JWT
alg Algoritmo ES256
kid ID chiave Deve corrispondere a una delle chiavi pubbliche elencate nel file di chiavi IAP, disponibile in due formati diversi: https://www.gstatic.com/iap/verify/public_key e https://www.gstatic.com/iap/verify/public_key-jwk

Assicurati che il JWT sia stato firmato con la chiave privata corrispondente alla rivendicazione kid del token. Innanzitutto, recupera la chiave pubblica da uno dei due seguenti:

  • https://www.gstatic.com/iap/verify/public_key. Questo URL contiene un dizionario JSON che mappa le rivendicazioni kid ai valori della chiave pubblica.
  • https://www.gstatic.com/iap/verify/public_key-jwk. Questo URL contiene le chiavi pubbliche IAP in JWKJWK.

Dopo aver ottenuto la chiave pubblica, utilizza una libreria JWT per verificare la firma.

IAP ruota periodicamente le chiavi pubbliche. Per assicurarti di poter sempre verificare i JWT, consulta Automatizzare la memorizzazione nella cache delle chiavi pubbliche.

Verificare il payload JWT

Verifica che il payload del JWT sia conforme ai seguenti vincoli:

Rivendicazioni del payload JWT
exp Scadenza Deve essere nel futuro. L'ora è misurata in secondi trascorsi dall'epoca di Unix. Concedi 30 secondi per la distorsione. La durata massima di un token è di 10 minuti + 2 * distorsione.
iat Ora di emissione Deve essere nel passato. L'ora è misurata in secondi trascorsi dall'epoca di Unix. Concedi 30 secondi per la distorsione.
aud Pubblico Deve essere una stringa con i seguenti valori:
  • App Engine: /projects/PROJECT_NUMBER/apps/PROJECT_ID
  • Compute Engine e GKE: /projects/PROJECT_NUMBER/global/backendServices/SERVICE_ID
  • Cloud Run: /projects/PROJECT_NUMBER/locations/REGION/services/SERVICE_NAME
iss Emittente Deve essere https://cloud.google.com/iap.
hd Dominio dell'account Se un account appartiene a un dominio ospitato, viene fornita la hd rivendicazione per distinguere il dominio a cui è associato l'account.
google Rivendicazione Google Se alla richiesta si applicano uno o più livelli di accesso i relativi nomi vengono memorizzati nell'oggetto JSON della google rivendicazione, sotto la chiave access_levels, come array di stringhe.

Quando specifichi una policy per i dispositivi e l'organizzazione ha accesso ai dati sul dispositivo, anche DeviceId viene memorizzato nell'oggetto JSON. Tieni presente che una richiesta inviata a un'altra organizzazione potrebbe non avere l'autorizzazione per visualizzare i dati sul dispositivo.

Puoi ottenere i valori per la stringa aud menzionata sopra accedendo alla Google Cloud console oppure utilizzando lo strumento a riga di comando gcloud.

Per ottenere i valori della stringa aud dalla Google Cloud console, vai alle impostazioni del proxy Identity-Aware Proxy per il tuo progetto, fai clic su Altro accanto alla risorsa del bilanciatore del carico e poi seleziona Pubblico JWT con intestazione firmata. La finestra di dialogo JWT con intestazione firmata visualizzata mostra la rivendicazione aud per la risorsa selezionata.

Se vuoi utilizzare lo strumento a riga di comando gcloud CLI gcloud per ottenere i valori della stringa aud, devi conoscere l'ID progetto. Puoi trovare l'ID progetto nella Google Cloud console scheda Informazioni sul progetto, quindi esegui i comandi specificati per ogni valore.

Numero progetto

Per ottenere il numero del progetto utilizzando lo strumento a riga di comando gcloud, esegui il comando seguente:

gcloud projects describe PROJECT_ID

Il comando restituisce un output simile al seguente:

createTime: '2016-10-13T16:44:28.170Z'
lifecycleState: ACTIVE
name: project_name
parent:
  id: '433637338589'
  type: organization
projectId: PROJECT_ID
projectNumber: 'PROJECT_NUMBER'

ID servizio

Per ottenere l'ID servizio utilizzando lo strumento a riga di comando gcloud, esegui il comando seguente:

gcloud compute backend-services describe SERVICE_NAME --project=PROJECT_ID --global

Il comando restituisce un output simile al seguente:

affinityCookieTtlSec: 0
backends:
- balancingMode: UTILIZATION
  capacityScaler: 1.0
  group: https://www.googleapis.com/compute/v1/projects/project_name/regions/us-central1/instanceGroups/my-group
connectionDraining:
  drainingTimeoutSec: 0
creationTimestamp: '2017-04-03T14:01:35.687-07:00'
description: ''
enableCDN: false
fingerprint: zaOnO4k56Cw=
healthChecks:
- https://www.googleapis.com/compute/v1/projects/project_name/global/httpsHealthChecks/my-hc
id: 'SERVICE_ID'
kind: compute#backendService
loadBalancingScheme: EXTERNAL
name: my-service
port: 8443
portName: https
protocol: HTTPS
selfLink: https://www.googleapis.com/compute/v1/projects/project_name/global/backendServices/my-service
sessionAffinity: NONE
timeoutSec: 3610

Recuperare l'identità dell'utente

Se tutte le verifiche precedenti hanno esito positivo, recupera l'identità dell'utente. Il payload del token ID contiene le seguenti informazioni sull'utente:

Identità utente del payload del token ID
sub Oggetto L'identificatore univoco e stabile dell'utente. Utilizza questo valore anziché l' x-goog-authenticated-user-id intestazione.
email Email dell'utente Indirizzo email dell'utente.
  • Utilizza questo valore anziché l' x-goog-authenticated-user-email intestazione.
  • A differenza di questa intestazione e della rivendicazione sub, questo valore non ha un prefisso dello spazio dei nomi.

Di seguito è riportato un codice campione per proteggere un'app con le intestazioni IAP firmate:

C#


using Google.Apis.Auth;
using Google.Apis.Auth.OAuth2;
using System;
using System.Threading;
using System.Threading.Tasks;

public class IAPTokenVerification
{
    /// <summary>
    /// Verifies a signed jwt token and returns its payload.
    /// </summary>
    /// <param name="signedJwt">The token to verify.</param>
    /// <param name="expectedAudience">The audience that the token should be meant for.
    /// Validation will fail if that's not the case.</param>
    /// <param name="cancellationToken">The cancellation token to propagate cancellation requests.</param>
    /// <returns>A task that when completed will have as its result the payload of the verified token.</returns>
    /// <exception cref="InvalidJwtException">If verification failed. The message of the exception will contain
    /// information as to why the token failed.</exception>
    public async Task<JsonWebSignature.Payload> VerifyTokenAsync(
        string signedJwt, string expectedAudience, CancellationToken cancellationToken = default)
    {
        SignedTokenVerificationOptions options = new SignedTokenVerificationOptions
        {
            // Use clock tolerance to account for possible clock differences
            // between the issuer and the verifier.
            IssuedAtClockTolerance = TimeSpan.FromMinutes(1),
            ExpiryClockTolerance = TimeSpan.FromMinutes(1),
            TrustedAudiences = { expectedAudience },
            TrustedIssuers = { "https://cloud.google.com/iap" },
            CertificatesUrl = GoogleAuthConsts.IapKeySetUrl,
        };

        return await JsonWebSignature.VerifySignedTokenAsync(signedJwt, options, cancellationToken: cancellationToken);
    }
}

Go

import (
	"context"
	"fmt"
	"io"

	"google.golang.org/api/idtoken"
)

// validateJWTFromAppEngine validates a JWT found in the
// "x-goog-iap-jwt-assertion" header.
func validateJWTFromAppEngine(w io.Writer, iapJWT, projectNumber, projectID string) error {
	// iapJWT := "YmFzZQ==.ZW5jb2RlZA==.and0" // req.Header.Get("X-Goog-IAP-JWT-Assertion")
	// projectNumber := "123456789"
	// projectID := "your-project-id"
	ctx := context.Background()
	aud := fmt.Sprintf("/projects/%s/apps/%s", projectNumber, projectID)

	payload, err := idtoken.Validate(ctx, iapJWT, aud)
	if err != nil {
		return fmt.Errorf("idtoken.Validate: %w", err)
	}

	// payload contains the JWT claims for further inspection or validation
	fmt.Fprintf(w, "payload: %v", payload)

	return nil
}

// validateJWTFromComputeEngine validates a JWT found in the
// "x-goog-iap-jwt-assertion" header.
func validateJWTFromComputeEngine(w io.Writer, iapJWT, projectNumber, backendServiceID string) error {
	// iapJWT := "YmFzZQ==.ZW5jb2RlZA==.and0" // req.Header.Get("X-Goog-IAP-JWT-Assertion")
	// projectNumber := "123456789"
	// backendServiceID := "backend-service-id"
	ctx := context.Background()
	aud := fmt.Sprintf("/projects/%s/global/backendServices/%s", projectNumber, backendServiceID)

	payload, err := idtoken.Validate(ctx, iapJWT, aud)
	if err != nil {
		return fmt.Errorf("idtoken.Validate: %w", err)
	}

	// payload contains the JWT claims for further inspection or validation
	fmt.Fprintf(w, "payload: %v", payload)

	return nil
}

Java


import com.google.api.client.http.HttpRequest;
import com.google.api.client.json.webtoken.JsonWebToken;
import com.google.auth.oauth2.TokenVerifier;

/** Verify IAP authorization JWT token in incoming request. */
public class VerifyIapRequestHeader {

  private static final String IAP_ISSUER_URL = "https://cloud.google.com/iap";

  // Verify jwt tokens addressed to IAP protected resources on App Engine.
  // The project *number* for your Google Cloud project via 'gcloud projects describe $PROJECT_ID'
  // The project *number* can also be retrieved from the Project Info card in Cloud Console.
  // projectId is The project *ID* for your Google Cloud Project.
  boolean verifyJwtForAppEngine(HttpRequest request, long projectNumber, String projectId)
      throws Exception {
    // Check for iap jwt header in incoming request
    String jwt = request.getHeaders().getFirstHeaderStringValue("x-goog-iap-jwt-assertion");
    if (jwt == null) {
      return false;
    }
    return verifyJwt(
        jwt,
        String.format("/projects/%s/apps/%s", Long.toUnsignedString(projectNumber), projectId));
  }

  boolean verifyJwtForComputeEngine(HttpRequest request, long projectNumber, long backendServiceId)
      throws Exception {
    // Check for iap jwt header in incoming request
    String jwtToken = request.getHeaders().getFirstHeaderStringValue("x-goog-iap-jwt-assertion");
    if (jwtToken == null) {
      return false;
    }
    return verifyJwt(
        jwtToken,
        String.format(
            "/projects/%s/global/backendServices/%s",
            Long.toUnsignedString(projectNumber), Long.toUnsignedString(backendServiceId)));
  }

  private boolean verifyJwt(String jwtToken, String expectedAudience) {
    TokenVerifier tokenVerifier =
        TokenVerifier.newBuilder().setAudience(expectedAudience).setIssuer(IAP_ISSUER_URL).build();
    try {
      JsonWebToken jsonWebToken = tokenVerifier.verify(jwtToken);

      // Verify that the token contain subject and email claims
      JsonWebToken.Payload payload = jsonWebToken.getPayload();
      return payload.getSubject() != null && payload.get("email") != null;
    } catch (TokenVerifier.VerificationException e) {
      System.out.println(e.getMessage());
      return false;
    }
  }
}

Node.js

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const iapJwt = 'SOME_ID_TOKEN'; // JWT from the "x-goog-iap-jwt-assertion" header

let expectedAudience = null;
if (projectNumber && projectId) {
  // Expected Audience for App Engine.
  expectedAudience = `/projects/${projectNumber}/apps/${projectId}`;
} else if (projectNumber && backendServiceId) {
  // Expected Audience for Compute Engine
  expectedAudience = `/projects/${projectNumber}/global/backendServices/${backendServiceId}`;
}

const oAuth2Client = new OAuth2Client();

async function verify() {
  // Verify the id_token, and access the claims.
  const response = await oAuth2Client.getIapPublicKeys();
  const ticket = await oAuth2Client.verifySignedJwtWithCertsAsync(
    iapJwt,
    response.pubkeys,
    expectedAudience,
    ['https://cloud.google.com/iap'],
  );
  // Print out the info contained in the IAP ID token
  console.log(ticket);
}

verify().catch(console.error);

PHP

namespace Google\Cloud\Samples\Iap;

# Imports Google auth libraries for IAP validation
use Google\Auth\AccessToken;

/**
 * Validate a JWT passed to your App Engine app by Identity-Aware Proxy.
 *
 * @param string $iapJwt The contents of the X-Goog-IAP-JWT-Assertion header.
 * @param string $cloudProjectNumber The project *number* for your Google
 *     Cloud project. This is returned by 'gcloud projects describe $PROJECT_ID',
 *     or in the Project Info card in Cloud Console.
 * @param string $cloudProjectId Your Google Cloud Project ID.
 */
function validate_jwt_from_app_engine(
    string $iapJwt,
    string $cloudProjectNumber,
    string $cloudProjectId
): void {
    $expectedAudience = sprintf(
        '/projects/%s/apps/%s',
        $cloudProjectNumber,
        $cloudProjectId
    );
    validate_jwt($iapJwt, $expectedAudience);
}

/**
 * Validate a JWT passed to your Compute / Container Engine app by Identity-Aware Proxy.
 *
 * @param string $iapJwt The contents of the X-Goog-IAP-JWT-Assertion header.
 * @param string $cloudProjectNumber The project *number* for your Google
 *     Cloud project. This is returned by 'gcloud projects describe $PROJECT_ID',
 *     or in the Project Info card in Cloud Console.
 * @param string $backendServiceId The ID of the backend service used to access the
 *     application. See https://cloud.google.com/iap/docs/signed-headers-howto
 *     for details on how to get this value.
 */
function validate_jwt_from_compute_engine(
    string $iapJwt,
    string $cloudProjectNumber,
    string $backendServiceId
): void {
    $expectedAudience = sprintf(
        '/projects/%s/global/backendServices/%s',
        $cloudProjectNumber,
        $backendServiceId
    );
    validate_jwt($iapJwt, $expectedAudience);