# Financial-grade API (FAPI 2.0) client

Adapt a client to the FAPI 2.0 Security Profile: private key JWT, pushed authorization requests, and DPoP sender-constrained tokens.

Requires: fapi

> **Note:** Available with the Advanced and Pro subscription.

Switching an application to the **FAPI 2.0 Security Profile** changes what its client has to send. A client that worked before will stop working: the profile replaces the client secret with a signed assertion, requires the authorization request to be pushed to a back channel first, and issues access tokens bound to a key the client holds.

This guide covers only the differences from the [Authorization Code flow with PKCE](https://dts-identity.com/docs/quickstarts/oidc-authorization-code.md). Read that guide first.

## What changes

| | Standard client | FAPI 2.0 client |
|---|---|---|
| Client authentication | Client secret | Private key JWT, signed PS256 |
| Authorization request | Parameters in the browser URL | Pushed first, browser gets a `request_uri` |
| PKCE | Recommended | Required, S256 |
| Access token | `Bearer` | `DPoP`, bound to your key |
| Token requests | One call | Two on first contact, for the DPoP nonce |

## Before you start

1. **Generate a key pair** for client authentication. RSA (2048 bits or more) or EC on the P-256 curve.
2. **Register the public key** on the application, then switch it to the FAPI 2.0 profile. See [Financial-grade API security](https://dts-identity.com/docs/integrations/applications.md#financial-grade-api-security) for the order to follow.
3. **Generate a second key pair** for DPoP proofs. Keep it separate from the client-authentication key so each has one job.
4. **Read the discovery document.** It now also lists `pushed_authorization_request_endpoint`, and `dpop_signing_alg_values_supported` tells you which algorithms proofs may use.

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

If the API your application calls issues JWT access tokens, also set that API's signing algorithm to PS256. See [APIs](https://dts-identity.com/docs/integrations/apis.md#resource-indicators-and-tokens).

## 1. Build a client assertion

Every call that used to carry the client secret now carries a short-lived JWT signed with your client-authentication private key. The examples use the JOSE library of each stack: [`jose`](https://www.npmjs.com/package/jose) for Node.js, [`PyJWT`](https://pypi.org/project/PyJWT/) (with the `crypto` extra) for Python, Nimbus JOSE + JWT for Java, `Microsoft.IdentityModel.JsonWebTokens` for C#, `lestrrat-go/jwx` for Go, `web-token/jwt-framework` for PHP, and `josekit` for Rust.

```js tab="Node.js" tab-group="lang"
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);
}
```

```python tab="Python" tab-group="lang"
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},
    )
```

```java tab="Java" tab-group="lang"
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();
}
```

```csharp tab="C#" tab-group="lang"
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
});
```

```go tab="Go" tab-group="lang"
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
}
```

```php tab="PHP" tab-group="lang"
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);
}
```

```rust tab="Rust" tab-group="lang"
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()
}
```

Two details decide whether this is accepted:

- **`aud` must be the issuer identifier.** Without a profile the endpoint URL is also accepted; under FAPI 2.0 it is not.
- **`alg` must be PS256.** The profile pins the signing algorithm for the application's assertions.

Send it on every token and pushed-authorization request as two form fields:

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

## 2. Push the authorization request

Instead of putting the parameters in the browser URL, post them to the pushed-authorization endpoint. The response is a one-time reference.

```bash
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>
```

A successful call answers `201` with:

```json
{
  "request_uri": "urn:ietf:params:oauth:request_uri:...",
  "expires_in": 60
}
```

- **`redirect_uri` must always be sent**, even when the application has exactly one registered. The profile removes the shortcut of omitting it.
- **PKCE is mandatory** here, with `code_challenge_method=S256`. A pushed request without a challenge is refused.
- The `request_uri` is single-use and expires within a minute. Push the request when the user is about to be redirected, not in advance.

## 3. Send the user to the authorization endpoint

The browser URL now carries only the client id and the reference:

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

The platform returns the user to your redirect URI with `code`, `state`, and an `iss` parameter naming the issuer. **Check `iss` as well as `state`** before continuing; it protects against a response being replayed from a different issuer.

## 4. Create a DPoP proof

A DPoP proof is a JWT signed with your DPoP private key, carrying the public key in its header. It is bound to one request: the method and URL are inside it.

```js tab="Node.js" tab-group="lang"
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);
}
```

```python tab="Python" tab-group="lang"
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},
    )
```

```java tab="Java" tab-group="lang"
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();
}
```

```csharp tab="C#" tab-group="lang"
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,
            },
        },
    });
}
```

```go tab="Go" tab-group="lang"
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
}
```

```php tab="PHP" tab-group="lang"
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);
}
```

```rust tab="Rust" tab-group="lang"
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` is the endpoint URL without query or fragment, and it has to match the URL you actually call, including scheme and host.

## 5. Exchange the code, twice

**A server nonce is required, so the first token request always fails.** This is expected, not an error in your setup: the response hands you a nonce to put into the next proof.

```bash
# 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>
```

The answer is `400` with `{"error":"use_dpop_nonce"}` and a `DPoP-Nonce` response header. Read that header, build a **new** proof containing it as the `nonce` claim, and repeat the identical request:

```js tab="Node.js" tab-group="lang"
let res = await tokenRequest(dpopProof('POST', tokenUrl));
if (!res.ok) {
  const nonce = res.headers.get('dpop-nonce');
  res = await tokenRequest(dpopProof('POST', tokenUrl, nonce));
}
```

```python tab="Python" tab-group="lang"
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))
```

```java tab="Java" tab-group="lang"
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));
}
```

```csharp tab="C#" tab-group="lang"
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()));
}
```

```go tab="Go" tab-group="lang"
res, _ := tokenRequest(dpopProof("POST", tokenURL, ""))
if res.StatusCode != http.StatusOK {
	nonce := res.Header.Get("DPoP-Nonce")
	res, _ = tokenRequest(dpopProof("POST", tokenURL, nonce))
}
```

```php tab="PHP" tab-group="lang"
$res = tokenRequest(dpopProof($dpopKey, 'POST', $tokenUrl));
if ($res->getStatusCode() !== 200) {
    $nonce = $res->getHeaderLine('DPoP-Nonce');
    $res = tokenRequest(dpopProof($dpopKey, 'POST', $tokenUrl, $nonce));
}
```

```rust tab="Rust" tab-group="lang"
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?;
}
```

Nonces are reused for a while, so cache the last one you received and start with it on the next request. Handle `use_dpop_nonce` at any time: when a nonce expires, the same exchange happens again.

A successful response differs from a standard one in a single, important way:

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

## 6. Call APIs with the token

`token_type` is `DPoP`, not `Bearer`, and the token is bound to your DPoP key. Every call to a resource needs both the token and a fresh proof for **that** request:

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

Sending the token as `Authorization: Bearer` fails. A resource that checks the binding compares the key in the proof against the confirmation claim in the token, so a stolen token is useless without the private key.

## Troubleshooting

- **`use_dpop_nonce` on every request.** The proof is missing the `nonce` claim, or you reused the previous proof instead of signing a new one. Each proof is single-use.
- **`invalid_client` when the same setup worked before the profile.** Either the assertion's `aud` is the endpoint URL rather than the issuer identifier, or it is signed with something other than PS256, or the `kid` does not match a registered key.
- **`invalid_dpop_proof`.** The `htu` does not match the URL called (a proxy rewriting the host is a common cause), or `htm` does not match the method, or the clock is off by more than a small margin.
- **`invalid_request` at the authorization endpoint.** The application requires a pushed request, so parameters cannot be sent in the browser URL any more. Push them first and pass the `request_uri`.
- **`request_uri` rejected as unknown.** It has already been used, or it expired. Push a fresh request.
- **The resource rejects the token.** Check that it is sent with the `DPoP` scheme and that the resource is validating the binding rather than expecting a bearer token.

## See also

- [Financial-grade API security](https://dts-identity.com/docs/integrations/applications.md#financial-grade-api-security) for the application settings and what the profile enforces.
- [APIs](https://dts-identity.com/docs/integrations/apis.md#resource-indicators-and-tokens) for the access-token signing algorithm.
- [OpenID Connect (Authorization Code + PKCE)](https://dts-identity.com/docs/quickstarts/oidc-authorization-code.md) for the base flow.
