Skip to Content

Client Financial-grade API (FAPI 2.0)

Adattare un client al FAPI 2.0 Security Profile: private key JWT, pushed authorization request e token sender-constrained con DPoP.

Requiresfapi

Nota: disponibile con l'abbonamento Advanced e Pro.

Il passaggio di un'applicazione al FAPI 2.0 Security Profile cambia ciò che il suo client deve inviare. Un client che funzionava prima smette di funzionare: il profilo sostituisce il client secret con un'asserzione firmata, richiede che la richiesta di autorizzazione venga prima trasmessa a un back channel ed emette access token vincolati a una chiave in possesso del client.

Questa guida tratta soltanto le differenze rispetto al flusso Authorization Code con PKCE. Conviene leggere prima quella guida.

Che cosa cambia

Client standardClient FAPI 2.0
Autenticazione del clientClient secretPrivate key JWT, firmato PS256
Richiesta di autorizzazioneParametri nell'URL del browserTrasmessa prima, il browser riceve un request_uri
PKCEConsigliatoObbligatorio, S256
Access tokenBearerDPoP, vincolato alla propria chiave
Richieste di tokenUna chiamataDue al primo contatto, per il nonce DPoP

Prima di iniziare

  1. Generare una coppia di chiavi per l'autenticazione del client. RSA (2048 bit o più) oppure EC sulla curva P-256.

  2. Registrare la chiave pubblica sull'applicazione, quindi passarla al profilo FAPI 2.0. Per l'ordine da seguire vedere Financial-grade API security.

  3. Generare una seconda coppia di chiavi per i DPoP proof. Va tenuta separata dalla chiave di autenticazione del client, così che ciascuna abbia un solo compito.

  4. Leggere il documento di discovery. Ora elenca anche pushed_authorization_request_endpoint, mentre dpop_signing_alg_values_supported indica quali algoritmi possono usare i proof.

    https://<your-domain>/.well-known/openid-configuration

Se l'API chiamata dalla propria applicazione emette access token JWT, impostare a PS256 anche l'algoritmo di firma di quell'API. Vedere API.

1. Costruire una client assertion

Ogni chiamata che prima trasportava il client secret trasporta ora un JWT di breve durata firmato con la propria chiave privata di autenticazione del client. Gli esempi utilizzano la libreria JOSE di ciascuno stack: jose per Node.js, PyJWT (con l'extra crypto) per Python, Nimbus JOSE + JWT per Java, Microsoft.IdentityModel.JsonWebTokens per C#, lestrrat-go/jwx per Go, web-token/jwt-framework per PHP e josekit per Rust.

import * as jose from 'jose';

const ISSUER = 'https://<your-domain>';
const CLIENT_ID = '<your-client-id>';

// Your client-authentication private key, plus the key id shown next to the
// registered key in the Admin Console.
const authKey = await jose.importPKCS8(process.env.CLIENT_AUTH_PRIVATE_KEY, 'PS256');
const KID = '<key-id-from-the-console>';

function clientAssertion() {
  return new jose.SignJWT({ jti: crypto.randomUUID() })
    .setProtectedHeader({ alg: 'PS256', kid: KID, typ: 'JWT' })
    .setIssuer(CLIENT_ID)
    .setSubject(CLIENT_ID)
    .setAudience(ISSUER)          // the issuer identifier, not the endpoint URL
    .setIssuedAt()
    .setExpirationTime('2m')
    .sign(authKey);
}
import os
import time
import uuid

import jwt

ISSUER = "https://<your-domain>"
CLIENT_ID = "<your-client-id>"

# Your client-authentication private key, plus the key id shown next to the
# registered key in the Admin Console.
AUTH_KEY = os.environ["CLIENT_AUTH_PRIVATE_KEY"]
KID = "<key-id-from-the-console>"

def client_assertion():
    now = int(time.time())
    return jwt.encode(
        {
            "jti": str(uuid.uuid4()),
            "iss": CLIENT_ID,
            "sub": CLIENT_ID,
            "aud": ISSUER,  # the issuer identifier, not the endpoint URL
            "iat": now,
            "exp": now + 120,
        },
        AUTH_KEY,
        algorithm="PS256",
        headers={"kid": KID},
    )
import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.RSASSASigner;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import java.time.Instant;
import java.util.Date;
import java.util.UUID;

static final String ISSUER = "https://<your-domain>";
static final String CLIENT_ID = "<your-client-id>";

// The key id shown next to the registered key in the Admin Console.
static final String KID = "<key-id-from-the-console>";

static String clientAssertion() throws Exception {
    // Your client-authentication private key
    var authKey = JWK.parseFromPEMEncodedObjects(System.getenv("CLIENT_AUTH_PRIVATE_KEY")).toRSAKey();
    var claims = new JWTClaimsSet.Builder()
        .jwtID(UUID.randomUUID().toString())
        .issuer(CLIENT_ID)
        .subject(CLIENT_ID)
        .audience(ISSUER) // the issuer identifier, not the endpoint URL
        .issueTime(new Date())
        .expirationTime(Date.from(Instant.now().plusSeconds(120)))
        .build();
    var jwt = new SignedJWT(
        new JWSHeader.Builder(JWSAlgorithm.PS256).keyID(KID).type(JOSEObjectType.JWT).build(),
        claims);
    jwt.sign(new RSASSASigner(authKey));
    return jwt.serialize();
}
using System.Security.Cryptography;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;

const string Issuer = "https://<your-domain>";
const string ClientId = "<your-client-id>";

// Your client-authentication private key, plus the key id shown next to the
// registered key in the Admin Console.
var authRsa = RSA.Create();
authRsa.ImportFromPem(Environment.GetEnvironmentVariable("CLIENT_AUTH_PRIVATE_KEY"));
var authKey = new RsaSecurityKey(authRsa) { KeyId = "<key-id-from-the-console>" };

string ClientAssertion() => new JsonWebTokenHandler().CreateToken(new SecurityTokenDescriptor
{
    Issuer = ClientId,
    Audience = Issuer, // the issuer identifier, not the endpoint URL
    Claims = new Dictionary<string, object> { ["sub"] = ClientId, ["jti"] = Guid.NewGuid().ToString() },
    Expires = DateTime.UtcNow.AddMinutes(2),
    SigningCredentials = new SigningCredentials(authKey, SecurityAlgorithms.RsaSsaPssSha256), // PS256
});
import (
	"os"
	"time"

	"github.com/google/uuid"
	"github.com/lestrrat-go/jwx/v2/jwa"
	"github.com/lestrrat-go/jwx/v2/jwk"
	"github.com/lestrrat-go/jwx/v2/jwt"
)

const issuer = "https://<your-domain>"
const clientID = "<your-client-id>"

// Your client-authentication private key, plus the key id shown next to the
// registered key in the Admin Console.
var authKey, _ = jwk.ParseKey([]byte(os.Getenv("CLIENT_AUTH_PRIVATE_KEY")), jwk.WithPEM(true))

const kid = "<key-id-from-the-console>"

func clientAssertion() []byte {
	authKey.Set(jwk.KeyIDKey, kid)
	token, _ := jwt.NewBuilder().
		JwtID(uuid.NewString()).
		Issuer(clientID).
		Subject(clientID).
		Audience([]string{issuer}). // the issuer identifier, not the endpoint URL
		IssuedAt(time.Now()).
		Expiration(time.Now().Add(2*time.Minute)).
		Build()
	signed, _ := jwt.Sign(token, jwt.WithKey(jwa.PS256, authKey))
	return signed
}
use Jose\Component\Core\AlgorithmManager;
use Jose\Component\KeyManagement\JWKFactory;
use Jose\Component\Signature\Algorithm\PS256;
use Jose\Component\Signature\JWSBuilder;
use Jose\Component\Signature\Serializer\CompactSerializer;

const ISSUER = 'https://<your-domain>';
const CLIENT_ID = '<your-client-id>';
const KID = '<key-id-from-the-console>';

// Your client-authentication private key, plus the key id shown next to the
// registered key in the Admin Console.
$authKey = JWKFactory::createFromKey(getenv('CLIENT_AUTH_PRIVATE_KEY'));

function clientAssertion($authKey): string {
    $jws = (new JWSBuilder(new AlgorithmManager([new PS256()])))
        ->create()
        ->withPayload(json_encode([
            'jti' => bin2hex(random_bytes(16)),
            'iss' => CLIENT_ID,
            'sub' => CLIENT_ID,
            'aud' => ISSUER, // the issuer identifier, not the endpoint URL
            'iat' => time(),
            'exp' => time() + 120,
        ]))
        ->addSignature($authKey, ['alg' => 'PS256', 'kid' => KID, 'typ' => 'JWT'])
        ->build();
    return (new CompactSerializer())->serialize($jws);
}
use std::env;
use std::time::{Duration, SystemTime};

use josekit::jws::{JwsHeader, PS256};
use josekit::jwt::{self, JwtPayload};
use uuid::Uuid;

const ISSUER: &str = "https://<your-domain>";
const CLIENT_ID: &str = "<your-client-id>";

// The key id shown next to the registered key in the Admin Console.
const KID: &str = "<key-id-from-the-console>";

fn client_assertion() -> String {
    let mut header = JwsHeader::new();
    header.set_key_id(KID);
    header.set_token_type("JWT");

    let mut payload = JwtPayload::new();
    payload.set_jwt_id(Uuid::new_v4().to_string());
    payload.set_issuer(CLIENT_ID);
    payload.set_subject(CLIENT_ID);
    payload.set_audience(vec![ISSUER]); // the issuer identifier, not the endpoint URL
    payload.set_issued_at(&SystemTime::now());
    payload.set_expires_at(&(SystemTime::now() + Duration::from_secs(120)));

    // Your client-authentication private key
    let signer = PS256.signer_from_pem(env::var("CLIENT_AUTH_PRIVATE_KEY").unwrap()).unwrap();
    jwt::encode_with_signer(&payload, &header, &signer).unwrap()
}

Due dettagli decidono se l'assertion viene accettata:

  • aud deve essere l'identificatore dell'issuer. Senza un profilo viene accettato anche l'URL dell'endpoint; sotto FAPI 2.0 no.
  • alg deve essere PS256. Il profilo fissa l'algoritmo di firma per le assertion dell'applicazione.

Va inviata con ogni richiesta di token e con ogni pushed authorization request, sotto forma di due campi del form:

client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer
client_assertion=<the JWT>

2. Trasmettere la richiesta di autorizzazione

Invece di inserire i parametri nell'URL del browser, occorre inviarli in POST all'endpoint di pushed authorization. La risposta è un riferimento monouso.

curl -X POST https://<your-domain>/oauth/par \
  -d client_id=<your-client-id> \
  -d response_type=code \
  -d redirect_uri=https://app.example.com/callback \
  -d scope='openid profile' \
  -d code_challenge=<CODE_CHALLENGE> \
  -d code_challenge_method=S256 \
  -d client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer \
  -d client_assertion=<the JWT>

Una chiamata riuscita risponde 201 con:

{
  "request_uri": "urn:ietf:params:oauth:request_uri:...",
  "expires_in": 60
}
  • redirect_uri va sempre inviato, anche quando l'applicazione ne ha registrato esattamente uno. Il profilo elimina la scorciatoia di ometterlo.
  • PKCE è obbligatorio in questo punto, con code_challenge_method=S256. Una richiesta trasmessa senza challenge viene rifiutata.
  • Il request_uri è monouso e scade entro un minuto. Conviene trasmettere la richiesta quando l'utente sta per essere reindirizzato, non in anticipo.

3. Inviare l'utente all'authorization endpoint

L'URL del browser ora contiene soltanto il client id e il riferimento:

https://<your-domain>/authorize
  ?client_id=<your-client-id>
  &request_uri=urn%3Aietf%3Aparams%3Aoauth%3Arequest_uri%3A...

La piattaforma riporta l'utente al proprio redirect URI con code, state e un parametro iss che indica l'issuer. Verificare iss oltre a state prima di proseguire; questo protegge dal replay di una risposta proveniente da un issuer diverso.

4. Creare un DPoP proof

Un DPoP proof è un JWT firmato con la propria chiave privata DPoP, che trasporta la chiave pubblica nel proprio header. È vincolato a una singola richiesta: il metodo e l'URL sono contenuti al suo interno.

const dpopKey = await jose.importPKCS8(process.env.DPOP_PRIVATE_KEY, 'ES256');
const dpopPublicJwk = await jose.exportJWK(await jose.importSPKI(process.env.DPOP_PUBLIC_KEY, 'ES256'));

function dpopProof(method, url, nonce) {
  return new jose.SignJWT({ jti: crypto.randomUUID(), htm: method, htu: url, ...(nonce ? { nonce } : {}) })
    .setProtectedHeader({ alg: 'ES256', typ: 'dpop+jwt', jwk: dpopPublicJwk })
    .setIssuedAt()
    .sign(dpopKey);
}
from cryptography.hazmat.primitives.serialization import load_pem_private_key
from jwt.algorithms import ECAlgorithm

dpop_key = load_pem_private_key(os.environ["DPOP_PRIVATE_KEY"].encode(), password=None)
dpop_public_jwk = ECAlgorithm.to_jwk(dpop_key.public_key(), as_dict=True)

def dpop_proof(method, url, nonce=None):
    claims = {"jti": str(uuid.uuid4()), "htm": method, "htu": url, "iat": int(time.time())}
    if nonce:
        claims["nonce"] = nonce
    return jwt.encode(
        claims, dpop_key,
        algorithm="ES256",
        headers={"typ": "dpop+jwt", "jwk": dpop_public_jwk},
    )
import com.nimbusds.jose.crypto.ECDSASigner;

static String dpopProof(String method, String url, String nonce) throws Exception {
    var dpopKey = JWK.parseFromPEMEncodedObjects(System.getenv("DPOP_PRIVATE_KEY")).toECKey();

    var claims = new JWTClaimsSet.Builder()
        .jwtID(UUID.randomUUID().toString())
        .claim("htm", method)
        .claim("htu", url)
        .issueTime(new Date());
    if (nonce != null) claims.claim("nonce", nonce);

    var jwt = new SignedJWT(
        new JWSHeader.Builder(JWSAlgorithm.ES256)
            .type(new JOSEObjectType("dpop+jwt"))
            .jwk(dpopKey.toPublicJWK())
            .build(),
        claims.build());
    jwt.sign(new ECDSASigner(dpopKey));
    return jwt.serialize();
}
var dpopEc = ECDsa.Create();
dpopEc.ImportFromPem(Environment.GetEnvironmentVariable("DPOP_PRIVATE_KEY"));
var dpopKey = new ECDsaSecurityKey(dpopEc);
var publicJwk = JsonWebKeyConverter.ConvertFromECDsaSecurityKey(
    new ECDsaSecurityKey(ECDsa.Create(dpopEc.ExportParameters(includePrivateParameters: false))));

string DpopProof(string method, string url, string? nonce = null)
{
    var claims = new Dictionary<string, object> { ["jti"] = Guid.NewGuid().ToString(), ["htm"] = method, ["htu"] = url };
    if (nonce is not null) claims["nonce"] = nonce;

    return new JsonWebTokenHandler().CreateToken(new SecurityTokenDescriptor
    {
        TokenType = "dpop+jwt",
        Claims = claims,
        SigningCredentials = new SigningCredentials(dpopKey, SecurityAlgorithms.EcdsaSha256), // ES256
        AdditionalHeaderClaims = new Dictionary<string, object>
        {
            ["jwk"] = new Dictionary<string, string>
            {
                ["kty"] = publicJwk.Kty, ["crv"] = publicJwk.Crv, ["x"] = publicJwk.X, ["y"] = publicJwk.Y,
            },
        },
    });
}
import "github.com/lestrrat-go/jwx/v2/jws"

var dpopKey, _ = jwk.ParseKey([]byte(os.Getenv("DPOP_PRIVATE_KEY")), jwk.WithPEM(true))

func dpopProof(method, url, nonce string) []byte {
	dpopPublicJwk, _ := dpopKey.PublicKey()

	builder := jwt.NewBuilder().
		JwtID(uuid.NewString()).
		Claim("htm", method).
		Claim("htu", url).
		IssuedAt(time.Now())
	if nonce != "" {
		builder = builder.Claim("nonce", nonce)
	}
	token, _ := builder.Build()

	headers := jws.NewHeaders()
	headers.Set("typ", "dpop+jwt")
	headers.Set("jwk", dpopPublicJwk)
	signed, _ := jwt.Sign(token, jwt.WithKey(jwa.ES256, dpopKey, jws.WithProtectedHeaders(headers)))
	return signed
}
use Jose\Component\Signature\Algorithm\ES256;

$dpopKey = JWKFactory::createFromKey(getenv('DPOP_PRIVATE_KEY'));

function dpopProof($dpopKey, string $method, string $url, ?string $nonce = null): string {
    $claims = ['jti' => bin2hex(random_bytes(16)), 'htm' => $method, 'htu' => $url, 'iat' => time()];
    if ($nonce !== null) {
        $claims['nonce'] = $nonce;
    }
    $jws = (new JWSBuilder(new AlgorithmManager([new ES256()])))
        ->create()
        ->withPayload(json_encode($claims))
        ->addSignature($dpopKey, ['alg' => 'ES256', 'typ' => 'dpop+jwt', 'jwk' => $dpopKey->toPublic()])
        ->build();
    return (new CompactSerializer())->serialize($jws);
}
use josekit::jws::ES256;

fn dpop_proof(method: &str, url: &str, nonce: Option<&str>) -> String {
    let pem = env::var("DPOP_PRIVATE_KEY").unwrap();
    let key_pair = ES256.key_pair_from_pem(&pem).unwrap();

    let mut header = JwsHeader::new();
    header.set_token_type("dpop+jwt");
    header.set_jwk(key_pair.to_jwk_public_key());

    let mut payload = JwtPayload::new();
    payload.set_jwt_id(Uuid::new_v4().to_string());
    payload.set_claim("htm", Some(method.into())).unwrap();
    payload.set_claim("htu", Some(url.into())).unwrap();
    payload.set_issued_at(&SystemTime::now());
    if let Some(nonce) = nonce {
        payload.set_claim("nonce", Some(nonce.into())).unwrap();
    }

    let signer = ES256.signer_from_pem(&pem).unwrap();
    jwt::encode_with_signer(&payload, &header, &signer).unwrap()
}

htu è l'URL dell'endpoint senza query né fragment e deve corrispondere all'URL effettivamente chiamato, schema e host compresi.

5. Scambiare il code, due volte

È richiesto un nonce del server, quindi la prima richiesta di token fallisce sempre. È un comportamento previsto, non un errore della propria configurazione: la risposta fornisce un nonce da inserire nel proof successivo.

# First attempt: no nonce yet
curl -i -X POST https://<your-domain>/oauth/token \
  -H 'DPoP: <proof without nonce>' \
  -d grant_type=authorization_code \
  -d code=<one-time-code> \
  -d redirect_uri=https://app.example.com/callback \
  -d code_verifier=<CODE_VERIFIER> \
  -d client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer \
  -d client_assertion=<the JWT>

La risposta è 400 con {"error":"use_dpop_nonce"} e un header di risposta DPoP-Nonce. Occorre leggere quell'header, costruire un nuovo proof che lo contenga come claim nonce e ripetere la richiesta identica:

let res = await tokenRequest(dpopProof('POST', tokenUrl));
if (!res.ok) {
  const nonce = res.headers.get('dpop-nonce');
  res = await tokenRequest(dpopProof('POST', tokenUrl, nonce));
}
res = token_request(dpop_proof("POST", token_url))
if not res.ok:
    nonce = res.headers.get("dpop-nonce")
    res = token_request(dpop_proof("POST", token_url, nonce))
var res = tokenRequest(dpopProof("POST", tokenUrl, null));
if (res.statusCode() != 200) {
    var nonce = res.headers().firstValue("DPoP-Nonce").orElseThrow();
    res = tokenRequest(dpopProof("POST", tokenUrl, nonce));
}
var res = await TokenRequest(DpopProof("POST", tokenUrl));
if (!res.IsSuccessStatusCode && res.Headers.TryGetValues("DPoP-Nonce", out var nonces))
{
    res = await TokenRequest(DpopProof("POST", tokenUrl, nonces.First()));
}
res, _ := tokenRequest(dpopProof("POST", tokenURL, ""))
if res.StatusCode != http.StatusOK {
	nonce := res.Header.Get("DPoP-Nonce")
	res, _ = tokenRequest(dpopProof("POST", tokenURL, nonce))
}
$res = tokenRequest(dpopProof($dpopKey, 'POST', $tokenUrl));
if ($res->getStatusCode() !== 200) {
    $nonce = $res->getHeaderLine('DPoP-Nonce');
    $res = tokenRequest(dpopProof($dpopKey, 'POST', $tokenUrl, $nonce));
}
let mut res = token_request(dpop_proof("POST", token_url, None)).await?;
if !res.status().is_success() {
    let nonce = res.headers().get("dpop-nonce").and_then(|v| v.to_str().ok()).map(String::from);
    res = token_request(dpop_proof("POST", token_url, nonce.as_deref())).await?;
}

I nonce restano validi per un certo tempo, quindi conviene memorizzare l'ultimo ricevuto e iniziare con quello alla richiesta successiva. use_dpop_nonce va gestito in qualsiasi momento: quando un nonce scade, lo stesso scambio si ripete.

Una risposta positiva si differenzia da una risposta standard in un unico aspetto, importante:

{
  "token_type": "DPoP",
  "access_token": "...",
  "id_token": "...",
  "expires_in": 3600
}

6. Chiamare le API con il token

token_type è DPoP, non Bearer, e il token è vincolato alla propria chiave DPoP. Ogni chiamata a una risorsa richiede sia il token sia un proof nuovo per quella richiesta:

curl https://api.example.com/orders \
  -H 'Authorization: DPoP <access_token>' \
  -H 'DPoP: <proof for GET https://api.example.com/orders>'

L'invio del token come Authorization: Bearer fallisce. Una risorsa che verifica il vincolo confronta la chiave presente nel proof con il claim di conferma contenuto nel token, quindi un token sottratto è inutile senza la chiave privata.

Risoluzione dei problemi

  • use_dpop_nonce a ogni richiesta. Nel proof manca il claim nonce, oppure è stato riutilizzato il proof precedente anziché firmarne uno nuovo. Ogni proof è monouso.
  • invalid_client quando la stessa configurazione funzionava prima del profilo. O l'aud dell'assertion è l'URL dell'endpoint anziché l'identificatore dell'issuer, oppure l'assertion è firmata con qualcosa di diverso da PS256, oppure il kid non corrisponde a una chiave registrata.
  • invalid_dpop_proof. L'htu non corrisponde all'URL chiamato (una causa frequente è un proxy che riscrive l'host), oppure htm non corrisponde al metodo, oppure l'orologio si discosta oltre un margine minimo.
  • invalid_request sull'authorization endpoint. L'applicazione richiede una pushed request, quindi i parametri non possono più essere inviati nell'URL del browser. Vanno trasmessi prima, passando poi il request_uri.
  • request_uri rifiutato come sconosciuto. È già stato utilizzato oppure è scaduto. Occorre trasmettere una nuova richiesta.
  • La risorsa rifiuta il token. Verificare che venga inviato con lo schema DPoP e che la risorsa validi il vincolo anziché attendersi un bearer token.

Vedere anche

In questa pagina