Skip to Content

Cliente Financial-grade API (FAPI 2.0)

Adapte un cliente al FAPI 2.0 Security Profile: private key JWT, pushed authorization requests y tokens sender-constrained con DPoP.

Requiresfapi

Nota: Disponible con las suscripciones Advanced y Pro.

Cambiar una aplicación al FAPI 2.0 Security Profile modifica lo que su cliente tiene que enviar. Un cliente que antes funcionaba dejará de funcionar: el perfil sustituye el client secret por una aserción firmada, exige que la solicitud de autorización se envíe antes a un back channel y emite access tokens vinculados a una clave que posee el cliente.

Esta guía cubre únicamente las diferencias respecto al flujo Authorization Code con PKCE. Lea antes esa guía.

Qué cambia

Cliente estándarCliente FAPI 2.0
Autenticación de clienteClient secretPrivate key JWT, firmado con PS256
Solicitud de autorizaciónParámetros en la URL del navegadorEnviada antes al back channel; el navegador recibe una request_uri
PKCERecomendadoObligatorio, S256
Access tokenBearerDPoP, vinculado a su clave
Solicitudes de tokenUna llamadaDos en el primer contacto, por el nonce de DPoP

Antes de empezar

  1. Genere un par de claves para la autenticación de cliente. RSA (2048 bits o más) o EC en la curva P-256.

  2. Registre la clave pública en la aplicación y cámbiela después al perfil FAPI 2.0. Consulte Financial-grade API security para saber en qué orden hacerlo.

  3. Genere un segundo par de claves para las pruebas DPoP. Manténgalo separado de la clave de autenticación de cliente, para que cada una tenga una única función.

  4. Lea el documento de discovery. Ahora incluye además pushed_authorization_request_endpoint, y dpop_signing_alg_values_supported indica qué algoritmos pueden utilizar las pruebas.

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

Si la API a la que llama su aplicación emite access tokens JWT, establezca también en PS256 el algoritmo de firma de esa API. Consulte APIs.

1. Construir una client assertion

Cada llamada que antes llevaba el client secret lleva ahora un JWT de corta duración firmado con su clave privada de autenticación de cliente. Los ejemplos utilizan la biblioteca JOSE de cada stack: jose para Node.js, PyJWT (con el extra crypto) para Python, Nimbus JOSE + JWT para Java, Microsoft.IdentityModel.JsonWebTokens para C#, lestrrat-go/jwx para Go, web-token/jwt-framework para PHP y josekit para 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()
}

Dos detalles deciden si esto se acepta:

  • aud debe ser el identificador del issuer. Sin perfil también se acepta la URL del endpoint; bajo FAPI 2.0, no.
  • alg debe ser PS256. El perfil fija el algoritmo de firma de las aserciones de la aplicación.

Envíela en cada solicitud de token y de pushed authorization como dos campos de formulario:

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

2. Enviar la solicitud de autorización al back channel

En lugar de poner los parámetros en la URL del navegador, envíelos por POST al endpoint de pushed authorization. La respuesta es una referencia de un solo uso.

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 llamada correcta responde con 201 y:

{
  "request_uri": "urn:ietf:params:oauth:request_uri:...",
  "expires_in": 60
}
  • La redirect_uri debe enviarse siempre, incluso cuando la aplicación tiene exactamente una registrada. El perfil elimina el atajo de poder omitirla.
  • PKCE es obligatorio aquí, con code_challenge_method=S256. Una solicitud enviada sin challenge se rechaza.
  • La request_uri es de un solo uso y caduca en menos de un minuto. Envíe la solicitud cuando el usuario esté a punto de ser redirigido, no por adelantado.

3. Enviar al usuario al endpoint de autorización

La URL del navegador solo lleva ya el client id y la referencia:

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

La plataforma devuelve al usuario a su redirect URI con code, state y un parámetro iss que nombra al issuer. Compruebe iss además de state antes de continuar; protege frente a la repetición de una respuesta procedente de otro issuer.

4. Crear una prueba DPoP

Una prueba DPoP es un JWT firmado con su clave privada DPoP que lleva la clave pública en su cabecera. Está vinculada a una única solicitud: el método y la URL van dentro.

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 es la URL del endpoint sin query ni fragmento, y tiene que coincidir con la URL que llama realmente, incluidos el esquema y el host.

5. Canjear el código, dos veces

Se exige un nonce del servidor, así que la primera solicitud de token siempre falla. Es el comportamiento esperado, no un error de su configuración: la respuesta le entrega un nonce para incluirlo en la siguiente prueba.

# 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 respuesta es un 400 con {"error":"use_dpop_nonce"} y una cabecera de respuesta DPoP-Nonce. Lea esa cabecera, construya una prueba nueva que lo contenga como claim nonce y repita la misma solicitud:

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?;
}

Los nonces se reutilizan durante un tiempo, así que guarde el último que haya recibido y empiece con él en la siguiente solicitud. Gestione use_dpop_nonce en cualquier momento: cuando un nonce caduca, se repite el mismo intercambio.

Una respuesta correcta se diferencia de una estándar en un único aspecto importante:

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

6. Llamar a las APIs con el token

token_type es DPoP, no Bearer, y el token está vinculado a su clave DPoP. Cada llamada a un recurso necesita tanto el token como una prueba nueva para esa solicitud:

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

Enviar el token como Authorization: Bearer falla. Un recurso que comprueba la vinculación compara la clave de la prueba con el claim de confirmación del token, de modo que un token robado es inútil sin la clave privada.

Solución de problemas

  • use_dpop_nonce en todas las solicitudes. A la prueba le falta el claim nonce, o ha reutilizado la prueba anterior en lugar de firmar una nueva. Cada prueba es de un solo uso.
  • invalid_client cuando la misma configuración funcionaba antes del perfil. O bien el aud de la aserción es la URL del endpoint en lugar del identificador del issuer, o está firmada con algo distinto de PS256, o el kid no se corresponde con ninguna clave registrada.
  • invalid_dpop_proof. El htu no coincide con la URL llamada (una causa habitual es un proxy que reescribe el host), o htm no coincide con el método, o el reloj se desvía más de un pequeño margen.
  • invalid_request en el endpoint de autorización. La aplicación exige una solicitud enviada al back channel, así que los parámetros ya no pueden ir en la URL del navegador. Envíelos antes y pase la request_uri.
  • La request_uri se rechaza por desconocida. Ya se ha utilizado o ha caducado. Envíe una solicitud nueva.
  • El recurso rechaza el token. Compruebe que se envía con el esquema DPoP y que el recurso valida la vinculación en lugar de esperar un bearer token.

Véase también

En esta página