# Klient Financial-grade API (FAPI 2.0)

Dostosuj klienta do FAPI 2.0 Security Profile: private key JWT, pushed authorization requests i tokeny sender-constrained z DPoP.

Requires: fapi

> **Uwaga:** Dostępne w subskrypcji Advanced i Pro.

Przełączenie aplikacji na **FAPI 2.0 Security Profile** zmienia to, co musi wysyłać jej klient. Klient, który działał wcześniej, przestanie działać: profil zastępuje client secret podpisaną asercją, wymaga wcześniejszego przesłania żądania autoryzacji kanałem zwrotnym i wystawia access tokeny powiązane z kluczem, który posiada klient.

Ten przewodnik omawia wyłącznie różnice względem [przepływu Authorization Code z PKCE](https://dts-identity.com/pl/docs/quickstarts/oidc-authorization-code.md). Tamten przewodnik przeczytaj najpierw.

## Co się zmienia

| | Klient standardowy | Klient FAPI 2.0 |
|---|---|---|
| Uwierzytelnianie klienta | Client secret | Private key JWT, podpisany PS256 |
| Żądanie autoryzacji | Parametry w adresie URL przeglądarki | Przesyłane wcześniej, przeglądarka dostaje `request_uri` |
| PKCE | Zalecane | Wymagane, S256 |
| Access token | `Bearer` | `DPoP`, powiązany z Twoim kluczem |
| Żądania tokenów | Jedno wywołanie | Dwa przy pierwszym kontakcie, ze względu na DPoP nonce |

## Zanim zaczniesz

1. **Wygeneruj parę kluczy** na potrzeby uwierzytelniania klienta. RSA (2048 bitów lub więcej) albo EC na krzywej P-256.
2. **Zarejestruj klucz publiczny** przy aplikacji, a następnie przełącz ją na profil FAPI 2.0. Kolejność, której należy się trzymać, opisuje sekcja [Financial-grade API security](https://dts-identity.com/pl/docs/integrations/applications.md#financial-grade-api-security).
3. **Wygeneruj drugą parę kluczy** na potrzeby DPoP proofs. Trzymaj ją oddzielnie od klucza uwierzytelniania klienta, aby każdy klucz miał jedno zadanie.
4. **Przeczytaj dokument discovery.** Wymienia teraz dodatkowo `pushed_authorization_request_endpoint`, a `dpop_signing_alg_values_supported` mówi, jakich algorytmów mogą używać proofs.

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

Jeśli API wywoływane przez Twoją aplikację wystawia access tokeny w formacie JWT, ustaw również algorytm podpisywania tego API na PS256. Zobacz [API](https://dts-identity.com/pl/docs/integrations/apis.md#resource-indicators-and-tokens).

## 1. Zbuduj client assertion

Każde wywołanie, które dotąd niosło client secret, niesie teraz krótko żyjący JWT podpisany kluczem prywatnym Twojego uwierzytelniania klienta. Przykłady korzystają z biblioteki JOSE właściwej dla danego stosu: [`jose`](https://www.npmjs.com/package/jose) dla Node.js, [`PyJWT`](https://pypi.org/project/PyJWT/) (z dodatkiem `crypto`) dla Pythona, Nimbus JOSE + JWT dla Javy, `Microsoft.IdentityModel.JsonWebTokens` dla C#, `lestrrat-go/jwx` dla Go, `web-token/jwt-framework` dla PHP oraz `josekit` dla Rusta.

```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()
}
```

O tym, czy zostanie to zaakceptowane, decydują dwa szczegóły:

- **`aud` musi być identyfikatorem issuera.** Bez profilu akceptowany jest również adres URL punktu końcowego; w ramach FAPI 2.0 już nie.
- **`alg` musi być PS256.** Profil ustala na stałe algorytm podpisywania asercji tej aplikacji.

Wysyłaj ją przy każdym żądaniu tokenu i pushed authorization request jako dwa pola formularza:

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

## 2. Prześlij żądanie autoryzacji

Zamiast umieszczać parametry w adresie URL przeglądarki, wyślij je metodą POST do punktu końcowego pushed authorization. Odpowiedzią jest jednorazowe odwołanie.

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

Udane wywołanie odpowiada kodem `201` i treścią:

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

- **`redirect_uri` trzeba wysyłać zawsze**, nawet gdy aplikacja ma zarejestrowany dokładnie jeden. Profil usuwa uproszczenie polegające na pominięciu tego parametru.
- **PKCE jest tutaj obowiązkowe**, z `code_challenge_method=S256`. Przesłane żądanie bez challenge zostaje odrzucone.
- Wartość `request_uri` jest jednorazowa i wygasa w ciągu minuty. Prześlij żądanie wtedy, gdy użytkownik ma zostać przekierowany, a nie z wyprzedzeniem.

## 3. Wyślij użytkownika do punktu końcowego autoryzacji

Adres URL w przeglądarce niesie teraz tylko client id i odwołanie:

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

Platforma odsyła użytkownika na Twój redirect URI z parametrami `code`, `state` oraz `iss`, który nazywa issuera. **Sprawdź `iss` tak samo jak `state`**, zanim przejdziesz dalej; chroni to przed powtórzeniem odpowiedzi pochodzącej od innego issuera.

## 4. Utwórz DPoP proof

DPoP proof to JWT podpisany Twoim prywatnym kluczem DPoP, niosący klucz publiczny w swoim nagłówku. Jest powiązany z jednym żądaniem: metoda i adres URL znajdują się w jego wnętrzu.

```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` to adres URL punktu końcowego bez części zapytania i bez fragmentu, i musi odpowiadać adresowi, który faktycznie wywołujesz, łącznie ze schematem i hostem.

## 5. Wymień kod, dwukrotnie

**Wymagany jest nonce serwera, więc pierwsze żądanie tokenu zawsze kończy się niepowodzeniem.** Tak ma być, to nie jest błąd w Twojej konfiguracji: odpowiedź przekazuje nonce, który należy umieścić w kolejnym proofie.

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

Odpowiedzią jest `400` z treścią `{"error":"use_dpop_nonce"}` i nagłówkiem odpowiedzi `DPoP-Nonce`. Odczytaj ten nagłówek, zbuduj **nowy** proof zawierający go jako claim `nonce` i powtórz identyczne żądanie:

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

Nonce'y są przez pewien czas używane ponownie, więc buforuj ostatni otrzymany i zaczynaj od niego przy kolejnym żądaniu. Obsługuj `use_dpop_nonce` w dowolnym momencie: gdy nonce wygaśnie, ta sama wymiana zachodzi ponownie.

Udana odpowiedź różni się od standardowej jednym, ale istotnym szczegółem:

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

## 6. Wywołuj API z tokenem

Wartość `token_type` to `DPoP`, a nie `Bearer`, a token jest powiązany z Twoim kluczem DPoP. Każde wywołanie zasobu wymaga zarówno tokenu, jak i świeżego proofu dla **tego** żądania:

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

Wysłanie tokenu jako `Authorization: Bearer` kończy się niepowodzeniem. Zasób, który sprawdza powiązanie, porównuje klucz z proofu z claimem potwierdzającym w tokenie, więc skradziony token jest bezużyteczny bez klucza prywatnego.

## Rozwiązywanie problemów

- **`use_dpop_nonce` przy każdym żądaniu.** W proofie brakuje claimu `nonce` albo użyto ponownie poprzedniego proofu zamiast podpisać nowy. Każdy proof jest jednorazowy.
- **`invalid_client`, choć ta sama konfiguracja działała przed włączeniem profilu.** Albo `aud` asercji jest adresem URL punktu końcowego zamiast identyfikatorem issuera, albo jest ona podpisana czymś innym niż PS256, albo `kid` nie odpowiada zarejestrowanemu kluczowi.
- **`invalid_dpop_proof`.** Wartość `htu` nie odpowiada wywołanemu adresowi URL (częstą przyczyną jest proxy przepisujące host), `htm` nie odpowiada metodzie albo zegar odbiega o więcej niż niewielki margines.
- **`invalid_request` na punkcie końcowym autoryzacji.** Aplikacja wymaga przesłanego wcześniej żądania, więc parametrów nie można już wysyłać w adresie URL przeglądarki. Prześlij je najpierw i przekaż `request_uri`.
- **`request_uri` odrzucone jako nieznane.** Zostało już użyte albo wygasło. Prześlij nowe żądanie.
- **Zasób odrzuca token.** Sprawdź, czy jest wysyłany ze schematem `DPoP` i czy zasób weryfikuje powiązanie, zamiast oczekiwać tokenu typu bearer.

## Zobacz również

- [Financial-grade API security](https://dts-identity.com/pl/docs/integrations/applications.md#financial-grade-api-security), po ustawienia aplikacji i opis tego, co wymusza profil.
- [API](https://dts-identity.com/pl/docs/integrations/apis.md#resource-indicators-and-tokens), po algorytm podpisywania access tokenów.
- [OpenID Connect (Authorization Code + PKCE)](https://dts-identity.com/pl/docs/quickstarts/oidc-authorization-code.md), po podstawowy przepływ.
