SenseCrypt Docs
Get StartedAdd Login quickstarts

FAPI 2.0 (Python)

Sign users in to a FAPI 2.0 application from a Python FastAPI app with private_key_jwt, a pushed authorization request, DPoP proofs and the server nonce retry.

Add Sign in with SenseCrypt to a Python FastAPI app whose OIDC application is on the FAPI 2.0/CIBA security profile (the FAPI 2.0 Security Profile and FAPI-CIBA). The app is a confidential client that holds a private key instead of a secret. It does by hand the four steps that most OIDC libraries leave to you: it authenticates with a signed client assertion (private_key_jwt), it pushes the authorization request (PAR, RFC 9126), it proves possession of its key with a DPoP (RFC 9449) proof on every call, and it answers the server's DPoP nonce challenge. The full list of what a FAPI 2.0 application must do follows. The face check happens on the user's phone, between the redirect and the callback.

Not on the FAPI 2.0 profile? The Python quickstart is shorter. An application on the Standard profile registered for private_key_jwt, DPoP and ES256 ID tokens (the default) can use the code on this page as it is, since every step it takes is also accepted from a Standard application. If it registered RS256 ID tokens, change the algorithm in verify_id_token to RS256.

Prerequisites

  • A SenseCrypt tenant on the FAPI 2.0/CIBA profile, or a tenant on the Standard profile where this application adopts it. See Security profiles.
  • A user in a group that you attach to the application. A user can sign in only if they belong to a group attached to the application, so an application with no group attached admits nobody. See Groups and access.
  • Python 3.10+.

What a FAPI 2.0 application must do

  • Push every authorization request. A direct /authorize from a FAPI application is refused invalid_request. Push the parameters to pushed_authorization_request_endpoint, then send the browser to authorization_endpoint with only client_id and the request_uri you got back. The request_uri is single-use and lives expires_in seconds (300 by default).
  • Authenticate with a signed assertion. The client_assertion is a JWT signed ES256 or PS256 (never RS256). iss and sub are your client_id. aud is the issuer identifier, as one string: the token or PAR endpoint URL is refused, and so is an array. Each assertion needs a fresh jti, because a jti is accepted once. Its exp may be at most 300 seconds ahead, plus 60 seconds for clock skew.
  • Send a DPoP proof on the PAR, token and UserInfo requests. At the token endpoint and at UserInfo the proof must carry a server nonce. A proof without one is answered use_dpop_nonce, with the nonce to use in a DPoP-Nonce header. Retry once, with that nonce, a new proof and a new client assertion. SenseCrypt authenticates the client before it checks the proof, so the first assertion's jti is already spent.
  • Use PKCE S256. It is always required for a FAPI application.
  • Redeem the code at once. A FAPI application's authorization code lives at most 60 seconds.
  • Read token_type. With DPoP the token response says "token_type": "DPoP" and the access token carries cnf.jkt, the thumbprint of your key. Present it as Authorization: DPoP <token> with a proof that carries ath. Presented as Bearer, it is refused.
  • Check iss on the callback. Every authorization response carries the issuer that produced it (the iss response parameter, RFC 9207). Refuse a callback whose iss is not your issuer.
  • Expect ES256 ID tokens. A FAPI application cannot register RS256.

Create a key pair

The application signs its assertions and its DPoP proofs with one P-256 key. This script writes the private key to client-key.pem and prints the public half as a JWK Set to register:

gen_key.py
import json

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec
from jwt.algorithms import ECAlgorithm

key = ec.generate_private_key(ec.SECP256R1())
with open("client-key.pem", "wb") as f:
    f.write(
        key.private_bytes(
            serialization.Encoding.PEM,
            serialization.PrivateFormat.PKCS8,
            serialization.NoEncryption(),
        )
    )

public_jwk = json.loads(ECAlgorithm.to_jwk(key.public_key()))
public_jwk.update(kid="key-1", alg="ES256")
print(json.dumps({"keys": [public_jwk]}, indent=2))

Keep client-key.pem on the server. Every key you register needs a kid, and an EC key must be on P-256. You can also sign the DPoP proofs with a separate key that you do not register, as long as every proof in one sign-in uses that same key.

Register the application

In the console, go to Applications → New OIDC application. In the Create application dialog:

  1. Security profile: FAPI 2.0/CIBA. In a FAPI 2.0/CIBA tenant it is already chosen and cannot be changed.
  2. Client type: Confidential.
  3. Token endpoint authentication: private_key_jwt.
  4. Client keys (JWKS): Inline JSON, and paste the JWK Set the script printed.
  5. Token binding: DPoP proofs.
  6. Allowed redirect URIs: http://localhost:8000/callback. A FAPI application takes https redirect URIs, and loopback http ones such as this for development.

Then attach a group that holds your test user on the application's Groups tab (see Groups and access).

Install dependencies

pip install "fastapi[standard]" httpx "pyjwt[crypto]"

httpx makes the calls to SenseCrypt, and pyjwt[crypto] signs the assertions and proofs and verifies the ID token.

export SENSECRYPT_ISSUER=https://<your-tenant>.sensecrypt.com
export SENSECRYPT_CLIENT_ID=your_client_id
export SENSECRYPT_KEY_FILE=client-key.pem
export SENSECRYPT_KEY_ID=key-1

Sign the assertion and the DPoP proof

The assertion's aud is the issuer from the discovery document, the same string the issuer puts in its tokens. A proof names the method and the URL it is for (htm, htu, with no query string), carries the latest server nonce, and, when it goes with an access token, that token's hash (ath).

main.py
import base64
import hashlib
import json
import os
import secrets
import time
from urllib.parse import urlencode

import httpx
import jwt
from cryptography.hazmat.primitives import serialization
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse, RedirectResponse
from jwt.algorithms import ECAlgorithm

ISSUER = os.environ["SENSECRYPT_ISSUER"]  # https://<your-tenant>.sensecrypt.com
CLIENT_ID = os.environ["SENSECRYPT_CLIENT_ID"]
KEY_ID = os.environ["SENSECRYPT_KEY_ID"]  # the kid you registered
REDIRECT_URI = "http://localhost:8000/callback"
JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"

with open(os.environ["SENSECRYPT_KEY_FILE"], "rb") as f:
    PRIVATE_KEY = serialization.load_pem_private_key(f.read(), password=None)
# The public half goes in every DPoP proof header. Never the private half.
PUBLIC_JWK = json.loads(ECAlgorithm.to_jwk(PRIVATE_KEY.public_key()))

app = FastAPI()
http = httpx.AsyncClient(timeout=15)
SESSIONS: dict[str, dict] = {}  # in memory for this sample; use a real session store
_disco: dict | None = None
_dpop_nonce: str | None = None  # the latest DPoP-Nonce the issuer sent


def b64url(raw: bytes) -> str:
    return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")


async def discovery() -> dict:
    global _disco
    if _disco is None:
        resp = await http.get(f"{ISSUER.rstrip('/')}/.well-known/openid-configuration")
        resp.raise_for_status()
        _disco = resp.json()
    return _disco


async def client_assertion() -> str:
    """A private_key_jwt assertion for one request: the issuer records each jti."""
    now = int(time.time())
    claims = {
        "iss": CLIENT_ID,
        "sub": CLIENT_ID,
        "aud": (await discovery())["issuer"],  # the issuer identifier, one string
        "jti": secrets.token_urlsafe(24),
        "iat": now,
        "exp": now + 60,
    }
    return jwt.encode(claims, PRIVATE_KEY, algorithm="ES256", headers={"kid": KEY_ID})


def dpop_proof(method: str, url: str, access_token: str | None = None) -> str:
    """A DPoP proof for one request (RFC 9449)."""
    claims = {
        "jti": secrets.token_urlsafe(24),
        "htm": method,
        "htu": url.split("?")[0],
        "iat": int(time.time()),
    }
    if _dpop_nonce:
        claims["nonce"] = _dpop_nonce
    if access_token:
        claims["ath"] = b64url(hashlib.sha256(access_token.encode("ascii")).digest())
    return jwt.encode(
        claims, PRIVATE_KEY, algorithm="ES256", headers={"typ": "dpop+jwt", "jwk": PUBLIC_JWK}
    )

Call the issuer, with the nonce retry

Every call goes through one helper. It keeps the latest DPoP-Nonce the issuer sent, and when the issuer asks for its nonce it retries once. At the token endpoint the ask is a 400 with "error": "use_dpop_nonce", and so is it at PAR, but only when the proof carries a nonce that is stale or not the issuer's: PAR does not require a nonce. At UserInfo the ask is a 401 whose WWW-Authenticate challenge names use_dpop_nonce.

main.py (continued)
def wants_nonce(resp: httpx.Response) -> bool:
    if resp.status_code == 401:
        return 'error="use_dpop_nonce"' in resp.headers.get("WWW-Authenticate", "")
    if resp.status_code == 400:
        try:
            return resp.json().get("error") == "use_dpop_nonce"
        except ValueError:
            return False
    return False


async def call_issuer(
    method: str, url: str, *, form: dict | None = None, access_token: str | None = None
) -> httpx.Response:
    """One call with a DPoP proof (and client authentication when `form` is a
    token or PAR request), retried once if the issuer asks for its nonce."""

    async def send() -> httpx.Response:
        global _dpop_nonce
        headers = {"DPoP": dpop_proof(method, url, access_token)}
        if access_token is not None:
            headers["Authorization"] = f"DPoP {access_token}"
        data = None
        if form is not None:
            data = {
                **form,
                "client_id": CLIENT_ID,
                "client_assertion_type": JWT_BEARER,
                "client_assertion": await client_assertion(),
            }
        resp = await http.request(method, url, data=data, headers=headers)
        if "DPoP-Nonce" in resp.headers:
            _dpop_nonce = resp.headers["DPoP-Nonce"]
        return resp

    resp = await send()
    if wants_nonce(resp):
        # send() signs a new proof with the nonce, and a new assertion: the
        # issuer checks the client before the proof, so the first jti is spent.
        resp = await send()
    return resp

Every successful answer from PAR, the token endpoint and UserInfo also carries a fresh DPoP-Nonce, so after the first call the retry is rare. A nonce stays valid for 300 seconds by default, and one nonce works at every endpoint of the tenant.

Push the request and redirect

/login pushes the whole authorization request, PKCE challenge included, under the client's own authentication. The DPoP proof on the push also binds the authorization code to your key, so only a holder of the key can redeem it. The browser carries only the request_uri.

main.py (continued)
@app.get("/login")
async def login():
    disco = await discovery()
    state, nonce = secrets.token_urlsafe(24), secrets.token_urlsafe(24)
    verifier = secrets.token_urlsafe(64)  # PKCE code_verifier, 86 characters
    resp = await call_issuer(
        "POST",
        disco["pushed_authorization_request_endpoint"],
        form={
            "response_type": "code",
            "redirect_uri": REDIRECT_URI,
            "scope": "openid profile email",
            "state": state,
            "nonce": nonce,
            "code_challenge": b64url(hashlib.sha256(verifier.encode("ascii")).digest()),
            "code_challenge_method": "S256",
        },
    )
    if resp.status_code != 201:
        raise HTTPException(502, f"PAR failed: {resp.text}")
    sid = secrets.token_urlsafe(32)
    SESSIONS[sid] = {"state": state, "nonce": nonce, "verifier": verifier}
    query = urlencode({"client_id": CLIENT_ID, "request_uri": resp.json()["request_uri"]})
    redirect = RedirectResponse(f"{disco['authorization_endpoint']}?{query}")
    redirect.set_cookie("sid", sid, httponly=True, samesite="lax")
    return redirect

Handle the callback

The callback checks iss and state, redeems the code within its 60 seconds, reads token_type, and verifies the ID token. /me then calls UserInfo with the DPoP-bound access token.

main.py (continued)
async def verify_id_token(id_token: str, expected_nonce: str) -> dict:
    disco = await discovery()
    kid = jwt.get_unverified_header(id_token).get("kid")
    jwks = (await http.get(disco["jwks_uri"])).json()  # cache this, refetch on a new kid
    key = next((k for k in jwks["keys"] if k.get("kid") == kid), None)
    if key is None:
        raise HTTPException(400, "The ID token is signed with an unknown key")
    claims = jwt.decode(
        id_token,
        jwt.PyJWK(key).key,
        algorithms=["ES256"],  # a FAPI application's ID tokens are ES256
        audience=CLIENT_ID,
        issuer=disco["issuer"],
        options={"require": ["exp", "iat", "iss", "aud", "sub"]},
    )
    if claims.get("nonce") != expected_nonce:
        raise HTTPException(400, "The ID token nonce does not match")
    return claims


@app.get("/callback")
async def callback(
    request: Request, code: str = "", state: str = "", iss: str = "", error: str = ""
):
    disco = await discovery()
    # RFC 9207: the response names the issuer that sent it.
    if iss != disco["issuer"]:
        raise HTTPException(400, "The response did not come from your issuer")
    pending = SESSIONS.pop(request.cookies.get("sid", ""), None)
    if pending is None or state != pending["state"]:
        raise HTTPException(400, "Unknown or mismatched state")
    if error:
        raise HTTPException(400, f"Sign-in did not complete: {error}")
    resp = await call_issuer(
        "POST",
        disco["token_endpoint"],
        form={
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": REDIRECT_URI,
            "code_verifier": pending["verifier"],
        },
    )
    if resp.status_code != 200:
        raise HTTPException(502, f"Token exchange failed: {resp.text}")
    tokens = resp.json()
    # DPoP: the access token is bound to this key (cnf.jkt). Send it with the
    # DPoP scheme and a proof, never as a Bearer token.
    if tokens["token_type"] != "DPoP":
        raise HTTPException(502, f"Expected a DPoP-bound token, got {tokens['token_type']}")
    claims = await verify_id_token(tokens["id_token"], pending["nonce"])
    sid = secrets.token_urlsafe(32)
    SESSIONS[sid] = {"sub": claims["sub"], "access_token": tokens["access_token"]}
    redirect = RedirectResponse("/me", status_code=303)
    redirect.set_cookie("sid", sid, httponly=True, samesite="lax")
    return redirect


@app.get("/me")
async def me(request: Request):
    user = SESSIONS.get(request.cookies.get("sid", ""))
    if user is None:
        return RedirectResponse("/login")
    disco = await discovery()
    resp = await call_issuer("GET", disco["userinfo_endpoint"], access_token=user["access_token"])
    if resp.status_code != 200:
        raise HTTPException(502, f"UserInfo failed: {resp.text}")
    return JSONResponse({"sub": user["sub"], "userinfo": resp.json()})

The sessions live in memory and the cookie is not marked Secure, which suits http://localhost only. Behind https, use a real session store and set secure=True on the cookie.

Run and verify

fastapi dev main.py   # serves on http://localhost:8000
  1. Open http://localhost:8000/login.
  2. Complete the sign-in on your phone.
  3. You land on /me, which shows your sub and the UserInfo claims.

Verify it worked: decode the access token (it is a JWT). Its cnf.jkt is the JWK thumbprint (RFC 7638) of your public key, and that is what makes the token useless without the key.

The requests on the wire

The push. The DPoP proof on the first push has no nonce yet, and PAR does not require one. (A later push carries the latest nonce, and a stale one there gets the same use_dpop_nonce challenge as at the token endpoint.)

POST /v1/idp/oidc/par
DPoP: <proof: htm=POST, htu={pushed_authorization_request_endpoint}>
Content-Type: application/x-www-form-urlencoded

response_type=code&redirect_uri=...&scope=openid%20profile%20email&state=...&nonce=...
&code_challenge=...&code_challenge_method=S256&client_id={client_id}
&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer
&client_assertion=<assertion: aud={issuer}>
HTTP/1.1 201 Created
DPoP-Nonce: <nonce>

{ "request_uri": "urn:ietf:params:oauth:request_uri:...", "expires_in": 300, "authorize_url": "..." }

The token request:

POST /v1/idp/oidc/token
DPoP: <proof: htm=POST, htu={token_endpoint}, nonce=<nonce from the PAR answer>>
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code&code=...&redirect_uri=...&code_verifier=...
&client_id={client_id}
&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer
&client_assertion=<new assertion: aud={issuer}>

A proof without a nonce, or with a stale one, gets the challenge, and the retry carries the nonce from the header and a new assertion:

HTTP/1.1 400 Bad Request
DPoP-Nonce: <fresh nonce>

{ "error": "use_dpop_nonce", "error_description": "A server-provided nonce is required in the DPoP proof" }

The answer to the retry:

{
  "access_token": "eyJ...",
  "id_token": "eyJ...",
  "token_type": "DPoP",
  "expires_in": 3600,
  "scope": "openid profile email"
}

Add offline_access to the scope for a refresh token. A refresh is the same token call with grant_type=refresh_token: a new assertion, a new proof, and the latest nonce.

Troubleshooting

  • invalid_client at PAR or the token endpoint. One opaque answer covers every client authentication failure. For a FAPI application check, in order: aud is exactly the discovery issuer (a string, not the endpoint URL); the algorithm is ES256 or PS256; the kid is one you registered; the jti is new; exp is no more than 300 seconds ahead. On a nonce retry, a reused assertion is the usual cause.
  • invalid_request and the error names a pushed authorization request. The browser was sent to /authorize with the parameters instead of the request_uri.
  • use_dpop_nonce again on the retry. The proof did not carry the nonce from the latest DPoP-Nonce header. Keep the latest value from every answer, success or error.
  • invalid_dpop_proof. Check typ (dpop+jwt), alg (ES256 or PS256), htm, and htu (the endpoint URL, without a query string). A proof is single-use, so sign a new one for every request. See Sender-constrained tokens.
  • invalid_grant at the token endpoint. The code is single-use and lives 60 seconds. The redirect_uri must be the one you pushed, the code_verifier must match, and the proof must come from the key that signed the PAR proof.
  • 401 at UserInfo with a DPoP challenge. The token went as Bearer, or the proof had no ath, or it came from another key.

Next steps

On this page