Risorse · 43

OAuth e OpenID Connect: verifica end-to-end di un'integrazione

Separazione delle autorizzazioni di accesso, delega e dati, quindi test di reindirizzamenti, token, sessioni e revoca.

Aggiornato · 9 min

Sala immaginaria vuota per la verifica delle identità con due chiavi di sicurezza, carta bianca e cartella bordeaux Illustrazione editoriale generata con IA

Obiettivi di questa guida

  • Separare l'identità dall'autorizzazione.
  • Rifiutare i reindirizzamenti e i token indesiderati.
  • Testare i rifiuti con la stessa attenzione riservata ai successi.
  • Verificare la rimozione dell'accesso dopo l'uscita o un incidente.

Verifica rapida

  • Quali provider ed emittenti sono previsti?
  • L'URI di reindirizzamento è registrato correttamente?
  • Un token ID viene utilizzato erroneamente come token di accesso?
  • Ogni risorsa verifica la proprietà?
  • Quali accessi sopravvivono alla revoca?

Metodo passo passo

  1. 1

    Rappresentare graficamente il flusso distribuito.

    Identificare il client pubblico o riservato, il browser, il server di autorizzazione, l'API e il provider OIDC. Registrare dove viaggiano i codici e i token, chi li memorizza e quali ruoli sono concessi. Un diagramma di vendita non definisce l'effettiva implementazione. Risultato

    Risultato: flusso, limiti di fiducia e proprietari dei componenti.

  2. 2

    Verifica della transazione di accesso.

    Utilizza il flusso di codice con PKCE appropriato per il client. Verifica S256, binding della transazione, reindirizzamenti registrati e protezione contro le richieste falsificate. Testa un URI imprevisto, un verificatore errato, codice riprodotto e un emittente imprevisto. RFC 9700 separa i requisiti e le raccomandazioni in base al tipo di client.

    Risultato: risultati dei test consentiti e negati.

  3. 3

    Convalida del token corretto.

    L'API convalida il proprio token di accesso in base al formato e alle regole del provider: firma o introspezione, emittente, destinatario, scadenza e autorizzazioni. Il client OIDC convalida separatamente il token di identità. Una firma valida non stabilisce che il token appartenga a questa API.

    Risultato: contratto di convalida e test di destinatario e scadenza.

  4. 4

    Verifica delle autorizzazioni aziendali

    Testa un oggetto di proprietà di un altro account, un ruolo inferiore, un campo privato e un'operazione amministrativa. Un ambito o un gateway autenticato non sostituiscono i controlli lato server sulla risorsa richiesta. Utilizza account e dati di test autorizzati.

    Risultato: matrice di ruoli, oggetti, operazioni e negazioni previste.

  5. 5

    Verifica della scadenza e della revoca

    Separa la sessione locale, la sessione del provider, il token di accesso e il token di aggiornamento. Testa la disconnessione, lo smarrimento del dispositivo, il cambio di ruolo, la rotazione della chiave di firma e l'interruzione del provider. Documenta il tempo di accesso residuo anziché presumere che la disconnessione revochi immediatamente tutto.

    Risultato: cronologia di rimozione dell'accesso ed eccezioni.

  6. 6

    Osservazione senza esporre segreti

    Registra il riferimento della transazione, la decisione di convalida, la categoria di errore e la versione della configurazione. Escludi codici, token e segreti. Prepara la diagnosi, l'arresto dell'integrazione e il ripristino a una configurazione convalidata; ripeti i test dopo le modifiche al provider. Risultato atteso

    Risultato: procedura operativa e verifiche di regressione.

Esempio pratico fittizio

Situazione illustrativa

Situazione esemplificativa: due client utilizzano lo stesso provider di identità. Un token valido per il primo client viene presentato all'API del secondo client.

Decisione e prove attese

L'API rifiuta il destinatario errato, registra una traccia senza token e non restituisce dati. Il rifiuto diventa un test di regressione.

Distinguere i meccanismi

MeccanismoScopoVerifica o limitazione
OAuth 2.0Delega l'accesso alle risorsePermessi oggetto lato server
OpenID ConnectStabilisci l'identità tramite un token ID convalidatoConvalida dell'emittente, del pubblico e della transazione
Sessione dell'applicazioneMantieni l'accesso all'applicazioneScadenza, invalidazione e protezione della sessione

Indicatori di gestione

IndicatoreCosa misuraPrima azione
Correggi i rifiutiCasi proibiti effettivamente bloccatiCorreggi ogni accettazione imprevista
Ritardo di revocaTempo fino alla scomparsa dell'accesso rilevanteVerifica sessioni e token separatamente
Errori di convalidaRifiuti per causa e versioneSepara gli attacchi dagli errori di configurazione

Errori comuni

  • Confondi l'autenticazione con l'autorizzazione
  • Accetta qualsiasi pubblico dopo aver verificato la firma
  • Registra URI di reindirizzamento generali
  • Registrazione dei token per Debug più semplice

Domande frequenti

Il PKCE sostituisce tutti i controlli?

No. Protegge lo scambio di codice nel flusso previsto; la convalida del token, i reindirizzamenti, l'autorizzazione aziendale e le sessioni devono comunque essere verificati.

Un JWT è un permesso?

JWT è un formato. Le attestazioni diventano utilizzabili solo dopo la convalida e l'applicazione delle regole API.

La convalida dovrebbe essere implementata da zero?

È preferibile utilizzare una libreria e una documentazione del provider mantenute, quindi testare la configurazione. Una libreria corretta può comunque essere configurata in modo errato.

Quali prove conservare per una verifica utile?

Conservare contesto dell’account, ruoli, risorsa e risposte API. L’accesso riuscito non dimostra permessi corretti; non registrare segreti di sessione.

OAuth/OIDC: destinatari e accesso

Le note dettagliate di questa edizione sono disponibili in inglese.

Which token belongs to which recipient? A testable validation contract

A secure OAuth/OIDC integration connects each token to its purpose, issuer and intended recipient. An ID token tells the OIDC client about authentication; an access token is presented to a protected resource. Successful sign-in alone does not authorise a read, a change or an AI agent’s tool call.

This reference covers a specific profile: an API consuming JWT access tokens under RFC 9068. OAuth 2.0 does not require every access token to use JWT. Clients must treat their access tokens as opaque; the resource server owns the validation contract. The examples below are fictional, with no secret or usable signature.

Where codes and tokens belong
Where codes and tokens belong Four independent rows show the recipients: code to token endpoint, ID token to OIDC client, access token to API, refresh token to token endpoint. This is not the full exchange sequence. Code → Token endpoint Transaction-bound exchange ID token → OIDC client Identity and client_id audience Access token → API / resource Check audience and permissions Refresh token → Token endpoint Renewal, not an API call Distinct destinations · conceptual map, not a network sequence

Four objects with distinct purposes

Four objects with distinct purposes
ObjectRecipient and purposeBoundary to retain
Authorisation codeAuthorisation server token endpoint: redeem the code within the intended transaction.The code is not an API permission; check binding to the client, redirect and PKCE.
ID tokenOIDC client: validate identity and transaction; aud contains its client_id.Do not reuse it as an API access credential; apply the OIDC rules for the relevant flow.
Access tokenResource server: access within the grant; its audience identifies the intended resource.Validate the token, then operation and object permissions. The client must not depend on its internal content.
Refresh tokenAuthorisation server token endpoint: obtain new access tokens.Do not send it to the resource server; its lifecycle differs from the local session.

Eight controls for the validation contract

Eight controls for the validation contract
ControlRule and scopeEvidence without tokens
Profile and typFor RFC 9068, check typ = at+jwt or application/at+jwt. Other profiles need their own rules; “any signed JWT” is too broad a contract.Configured profile and a rejected ID/access token confusion case.
Algorithm and keysVerify the signature with the expected issuer’s keys and algorithms allowed by configuration. RFC 9068 excludes alg = none; a received value does not set policy by itself.Cryptographic policy version and result, with no secret material.
Issuer issCompare exactly with the expected issuer. A similar host, path or suffix does not establish trust.Configuration reference and issuer_mismatch reason.
Audience audThe expected recipient must appear in aud. An audience array is possible; finding the recipient does not replace other checks.Expected resource and a test using a token intended for another API.
Expiry expCurrent time must precede exp; any small clock leeway is an explicit policy. The teaching fixture uses zero seconds of leeway.Test clock, configured leeway and an exercised expiry boundary.
Scopes and objectBind each scope to the resource and operation. Then check ownership, tenant and business policy on the server. RFC 9068 does not define all this authorisation.Action, test object, applied rule and a cross-tenant denial.
OIDC transaction and PKCEIf nonce was sent, verify its presence and equality in the ID token. RFC 9700 requires PKCE for public clients and recommends it for confidential clients; bind the challenge to the transaction, with S256 recommended.Wrong nonce, replayed code and wrong code_verifier tests in the authorised flow.
Access lifetime and removalSeparate access-token expiry, renewal and application session. RFC 9700 requires sender constraint or rotation to detect refresh-token replay for public clients.Residual access timeline, user departure and an exercised revocation procedure.
Read fictional claims without treating them as proof

Teaching clock: 2026-10-22 at 10:00:00 UTC. The JSON contains a readable header and claims only; no signed JWT serialization is supplied. exp is 10:05:00 UTC and iat is 09:59:00 UTC. The .example domains and identifiers belong solely to this scenario.

{
    "header": {
        "typ": "at+jwt",
        "alg": "RS256",
        "kid": "training-key-01"
    },
    "claims": {
        "iss": "https://identity.example/",
        "sub": "training-subject-17",
        "aud": "https://api.example/evidence",
        "exp": 1792663500,
        "iat": 1792663140,
        "jti": "training-event-001",
        "client_id": "training-console",
        "scope": "evidence:read"
    }
}

Decoding JSON does not validate a signature or establish trust in keys. Where stated, cryptography is an exercise assumption, never a check performed by this page. The profile also has required claims including sub, client_id, iat and jti: the eight-control table is not a complete validator. A subject does not necessarily identify a person; jti alone does not implement replay protection.

Ten review cases: decision, limit and expected evidence

01 · Token intended for the API: continue to business checks

Situation: iss, aud, typ and exp match the fictional contract; evidence:read is present. Signature verification is assumed solely for the exercise.

Decision: continue to operation and object checks, without automatically declaring “access allowed”. Expected evidence: business rule and test object reviewed separately.

02 · Assumed correct signature, wrong audience

Change: aud targets https://api.example/billing rather than the evidence resource. Other assumptions remain the same.

Decision: reject this token for this API. A correct signature does not change its recipient. Expected evidence: no resource content returned and a token-free audience failure record.

03 · Different issuer with plausible claims

Change: iss is https://other-identity.example/. An HTTPS URL does not make it equivalent to the configured issuer.

Decision: reject the issuer match. Expected evidence: exact comparison with https://identity.example/ and a regression test.

04 · Expiry reached at the exact second

Change: exp equals the test clock, 10:00:00 UTC, with zero seconds of leeway in this fixture.

Decision: reject as expired. “Now is before exp” is false at equality; this example does not establish a universal clock policy. Expected evidence: tests before, at and after the boundary under the real policy.

05 · ID token presented as an access token

Change: a fictional ID token has typ = JWT and aud = training-console. It targets the OIDC client.

Decision: reject it as an RFC 9068 JWT access token. Validating it at the OIDC client does not turn it into an access token. Expected evidence: separate validation rules for each token type.

06 · Write scope presented for a read operation

Change: scope is evidence:write while the call requires evidence:read.

Decision: deny the read under the exercise policy, which defines no write → read implication. Scope names and relationships belong to the contract. Expected evidence: an explicit operation/scope matrix, without inferring permissions from names.

07 · Readable JSON, unverified cryptography

Situation: the JSON is readable and values appear to match, but cryptographic validation and trusted keys are not established.

Decision: stop acceptance; the state is unverified. Expected evidence: configured library output and trust-contract checks. Reading claims alone must not release protected data.

08 · Correct token, another tenant’s object

Situation: test token checks are assumed to pass. The requested object belongs to another tenant and business policy denies this read.

Decision: deny the object. evidence:read does not grant access to every account’s evidence. Expected evidence: server-side cross-tenant test and no leakage through content or returned fields.

09 · Audience array containing the expected resource

Change: aud contains https://api.example/evidence and https://api.example/archive. The expected resource is listed.

Decision: this audience check can pass; continue all other checks. An array is not a wildcard. Expected evidence: scopes remain meaningful for the resource, with no ambiguous grant.

10 · ID token nonce differs from the transaction

Separate OIDC transaction, outside the API cases: sent nonce = training-transaction-A; received nonce = training-transaction-B.

Decision: reject the ID token for this transaction under OIDC Core §3.1.3.7. This does not replace PKCE or API rules. Expected evidence: compare with the original transaction and test missing nonce when one was sent.

Six useful acceptance-review records

  • Map clients, issuers, APIs and expected audiences, with an owner for each boundary.
  • Versioned validation contract: format, libraries, trusted keys, algorithms and clock leeway.
  • Action, scope, tenant and object matrix; state denials and the permission implications actually defined.
  • Synthetic fixtures, a fixed clock, negative variants and observed results in the authorised environment.
  • Separate session, access-token and refresh-token timelines during departure, revocation and provider outage.
  • Redacted log: internal transaction reference, policy version, decision reason and date; exclude tokens, codes and secrets.

Primary sources and reading scope

Sources reviewed on

Riferimenti ufficiali

I riferimenti supportano il metodo. Adattare i controlli al proprio contesto; non costituiscono una certificazione. I titoli dei riferimenti originali e i documenti di origine potrebbero essere in un'altra lingua.

Riferimenti consultati il .