Skip to main content

Didit Authentication Code Exchange and JWT Verification With JWKS

Exchange the one-time code at POST {origin}/token/ within 60 seconds for access, ID and refresh tokens, then verify the ES256 access token against your issuer's JWKS and cache keys by kid.

Didit Authentication Code Exchange and JWT Verification With JWKS

Contents

In this guide

Jump to the part you need.

If you're adding Didit sign-in to an app with a protected backend, use the OAuth 2.0 authorization code flow with PKCE S256. The browser returns to your redirect URL with code and state, your app exchanges the code at POST {issuer}/token/, and your backend verifies the ES256 access token against your application's JWKS. The first 50,000 active users each month are free, then $0.02 per additional active user per month. Each code works once and expires in 60 seconds.

Last updated: November 26, 2026. Prices checked against the live Didit price feed on November 26, 2026.

Didit Authentication code exchange and JWT verification at a glance
ItemValue
FlowOAuth 2.0 authorization code with PKCE, S256 only
Live issuerhttps://<name>.auth.didit.me, or your custom domain once it is active
Sandbox issuerhttps://<name>.sandbox.auth.didit.me
Sign-in page{issuer}/sign-in with redirect_uri, state, code_challenge, code_challenge_method=S256
Code lifetime60 seconds, one use
Token endpointPOST {issuer}/token/, JSON or form-encoded body
Tokens returnedaccess_token, id_token, refresh_token, token_type, expires_in, session_id
SigningES256 (P-256 keys), the key named in the kid header
Public keysGET {issuer}/.well-known/jwks.json
Key cacheCache-Control: public, max-age=300; keys rotate every 30 days
Access token lifetimeAt most 5 minutes
Session checkGET {issuer}/session/ before a sensitive action
PriceFirst 50,000 authentication active users each month free, then $0.02 per active user per month

Start free in the sandbox at business.didit.me, no sales call. Didit Authentication is the product page, the technical contract is in the Authentication overview, every number sits on didit.me/pricing, and developers who want an assistant on the build can connect it through the Didit MCP server.

The Use Didit with MCP guide, showing how to connect the hosted MCP server to an AI assistant
Use the Didit MCP setup guide to connect a supported AI assistant.

What you are building

In the browser quickstart, the app starts sign-in, keeps the PKCE verifier and state, and holds the tokens. Your backend verifies the access token on every protected request and decides what the person may do. Your sign-in origin, https://<slug>.auth.didit.me or your verified custom domain, serves the hosted pages, the token endpoint, the session, discovery and the signing keys we sign with.

The publishable key can appear in client code. Keep the Authentication secret key and verification API key off browser and mobile clients. The Authentication runtime endpoints here require neither key. Clients are public: there is no client secret, client_id is your application ID, and PKCE with S256 protects the code exchange.

Every call on this integration uses end-user credentials or none at all. Never send your verification API key or a console token to the sign-in, token, session, discovery or JWKS endpoints.

The exchange, in one place

The token endpoint is POST {issuer}/token/ on your application's sign-in origin. The body carries grant_type=authorization_code, the code from the callback, your code_verifier and the same redirect_uri you sent to /sign-in. It can be JSON or form-encoded. Each code works once and lasts 60 seconds, so exchange it inside the callback handler.

curl --fail-with-body "${DIDIT_AUTH_ISSUER}/token/" \
  -H 'Content-Type: application/json' \
  -d '{
    "grant_type": "authorization_code",
    "code": "CODE_FROM_CALLBACK",
    "code_verifier": "YOUR_PKCE_VERIFIER",
    "redirect_uri": "http://localhost:3000/auth/callback"
  }'
{
  "access_token": "eyJhbGciOiJFUzI1NiIs...",
  "id_token": "eyJhbGciOiJFUzI1NiIs...",
  "refresh_token": "N4yZTl6y24YKYq77X_SO...",
  "token_type": "Bearer",
  "expires_in": 299,
  "session_id": "c9abf6cc-2d64-4bf2-b31e-a4d09a070ab1"
}

The redirect_uri above is the sandbox callback used throughout this guide. Substitute your own exact registered redirect URI when you move to live.

Your backend receives the access_token, and that is the value it verifies on every protected request. The id_token carries identity claims and binds the sign-in to your nonce when you sent one. The refresh_token rotates whenever it is used, so store the newest one each time. expires_in reports how much access-token lifetime is left, and session_id identifies the session this exchange created.

Prerequisites

What you need before the first code exchange
RequirementWhat you needWhere it is set
PlanAny plan. Sandbox testing is free and unlimited, and the first 50,000 authentication active users each month are freedidit.me/pricing
ApplicationA Sandbox application, where Authentication is on from the start, or a Live application with Authentication turned on from the Products pageBusiness Console
Client typePublic client, no secret. client_id equals your application IDTokens and JWKS
Redirect URLAn exact registered redirect URL, matched character by characterAuthentication > Security and sessions > Redirect URLs and allowed origins
Allowed originRequired for the browser-based sandbox quickstart, so the browser can reach your application's Didit origin. The cURL example can be run independently of that browser settingSame console page
Sign-in methodAt least one method turned on, or the hosted page has nothing to offerAuthentication > Sign-in methods
Publishable keyUsed by the SDK quickstart: pk_test_ in Sandbox, pk_live_ live. Public, and it encodes the issuerAuthentication > Developers
RuntimeThe quickstart uses Node.js 20 or later. Backend verification can use a Didit server SDK or a JWT library with ES256 and JWKS supportServer SDKs

Step by step, from the console to a verified token

  1. Register the callback and the allowed origin. In the Business Console, use the application switcher to select your Sandbox application, open Authentication, then Security and sessions, then Redirect URLs and allowed origins. Add the Redirect URL http://localhost:3000/auth/callback and the Allowed origin http://localhost:3000. We only return a person to a redirect URL you registered, character by character, and the allowed origin is what lets the browser exchange the code with your application's Didit origin.

  2. Turn on a sign-in method and copy the publishable key. Open Authentication then Sign-in methods and turn on Email code. A new application starts with every method off, and the hosted page offers only the methods you turn on. Passkeys work too, and Google works in Sandbox with Didit's test credentials. Then open Authentication then Developers and copy the Publishable key, which starts with pk_test_ in Sandbox. Never put the secret key in browser or mobile code.

  3. Start sign-in with state and a PKCE challenge. Open the hosted page, which is the authorization_endpoint from discovery:

    {issuer}/sign-in?redirect_uri=...&state=...&code_challenge=...&code_challenge_method=S256

    redirect_uri must exactly match a registered URL. state holds up to 512 characters and you check it on the callback. code_challenge is the base64url SHA-256 of your verifier and is exactly 43 characters, with code_challenge_method set to S256. nonce is optional and is copied into the ID token so you can bind it to this sign-in. The JavaScript SDK builds this request for you after npm install @didit-protocol/auth.

  4. Exchange the code at POST {issuer}/token/. The callback receives code and state. Compare the returned state with the value you saved for that sign-in attempt, and stop before the exchange if it is missing or differs. Then send the body shown above, once, within 60 seconds, with the verifier you kept for that attempt.

  5. Verify the access token on your server, on every protected request. Send the token from the browser in the Authorization header and check it server-side with the JavaScript Authentication SDK's server-side verifyToken helper.

    Required before you authorize a request: the sample below is the quickstart's signature, issuer and expiry example, not a complete guard. The object it returns contains only personId and vendorData. Before returning those fields, require a present, unexpired exp, require aud to match your application ID, require the JWT header typ to be at+jwt, and reject a non-null act on routes that do not accept agents.

    import { verifyToken } from "@didit-protocol/auth/server";
    
    export async function authenticate(request: Request) {
      const header = request.headers.get("authorization") ?? "";
      const token = header.startsWith("Bearer ") ? header.slice(7) : "";
      try {
        const claims = await verifyToken(token, { publishableKey: process.env.DIDIT_PUBLISHABLE_KEY });
        return { personId: claims.sub, vendorData: claims.vendor_data };
      } catch {
        return null;
      }
    }

    Other languages verify the same token through the seven server SDKs for Python, Node.js, Go, Java, PHP, Ruby and .NET, listed in the server SDKs overview.

  6. Verify with any JWT library when you are not on a Didit SDK. The documented flow is the same either way: read the keys from {issuer}/.well-known/jwks.json, accept ES256 only, require iss to be your issuer without a trailing slash and aud to be your application ID, require a present and unexpired exp, require the access-token header type at+jwt, and apply the route's act rule. Set DIDIT_AUTH_ISSUER and DIDIT_APPLICATION_ID from your application settings so those checks read the right values.

  7. Check the live session before a sensitive action, then watch the sign-in. An access token stays valid until it expires, within 5 minutes, so call GET {issuer}/session/ before a payout, a bank account change or an email change, sending the access token as Authorization: Bearer <access token>. The session check fails at once when the session was revoked, went idle or expired, when the person was blocked, or when the session no longer meets your MFA policy. Before risky actions, ask us whether the person has to verify again, and act only on an approved step-up your backend read itself.

    A biometric selfie step used as step-up authentication by Didit
    Step-up verification, such as a selfie, sits in front of sensitive actions and is a separate decision from the access token.

    Then open Authentication then Sign-ins in the console. Each sign-in is listed with the method used, and the person's timeline shows it next to their verifications and transactions. Subscribe your server to the auth.signup, auth.login and auth.new_device webhooks for events instead of polling.

    A session overview with its warnings in the Didit Business Console
    A person's session overview in the Business Console, where sign-ins sit next to verifications.

Field and event map

Key fields and events for the code exchange and token verification
FieldWhere it appearsRule or action
redirect_uri/sign-in and /token/Must match a registered redirect URL character by character
state/sign-in, returned on the callbackUp to 512 characters; compare it before the exchange
code_challenge/sign-inBase64url SHA-256 of the verifier, exactly 43 characters
code_challenge_method/sign-inS256 only
nonce/sign-inOptional, copied into the ID token to bind the sign-in
scope/sign-inopenid, email, phone, profile, offline_access
codeCallback, then /token/One use, 60 seconds
code_verifier/token/The verifier whose SHA-256 produced the challenge
grant_type/token/authorization_code, or refresh_token for a refresh
access_token/token/ responseSend as Authorization: Bearer to your backend, never trust it unverified
id_token/token/ responseSigned identity claims; bind it with nonce
refresh_token/token/ responseRotates on every use
expires_in/token/ responseSeconds of access-token lifetime remaining. Access tokens last at most 5 minutes.
session_id/token/ responseIdentifier of the session returned by the exchange
issJWT claimYour issuer, without a trailing slash
audJWT claimYour application ID
subJWT claimThe person id, read as claims.sub
vendor_dataJWT claimYour own reference, read as claims.vendor_data
kidJWT headerNames the signing key inside the JWKS
auth.signup, auth.login, auth.new_deviceWebhook eventsSubscribe on your server for sign-in events

Troubleshooting: exchange errors, key lookups and rejected sessions

We return invalid_grant when the code, verifier, redirect URI or sign-in eligibility fails validation. Read the status first, then the field names in the body, and use the table below for the documented cases.

Causes and fixes for one-time-code exchanges, key lookups and session checks
Response or symptomLikely causeFix
400 {"error": "invalid_grant"}The code is unknown, already used or older than 60 secondsExchange once, in the callback, immediately
400 {"error": "invalid_grant"}The verifier does not match the challenge you sentKeep the verifier with the sign-in attempt; do not regenerate it on the callback
400 {"error": "invalid_grant"}redirect_uri does not match, or is no longer registeredSend the exact registered URL, including scheme, port and trailing slash
400 {"error": "invalid_grant"}The person is blocked, or their email is no longer verifiedCheck the account status in the console. Keep blocked accounts denied and require email reverification when the address is no longer verified.
400 {"error": "invalid_grant"}You turned off the sign-in method the person usedTurn the method back on under Sign-in methods
400 {"error": "invalid_client"}client_id is not your application IDOmit client_id or send the application ID exactly
400 {"error": "mfa_required"}The sign-in did not meet your MFA policyThe hosted pages handle this; on your own screens handle the step yourself
400 {"<field>": [...]}A field is missing or invalidRead the field name, for example non_field_errors when a grant lacks required fields
400 {"<field>": "unknown_field"}The body has a field the endpoint does not takeRemove the field and resend
Offline verification fails, no key matches the kidUnknown kid against a stale JWKSRefetch the JWKS once, at most once a minute, then reject if the key is still missing
A newly issued token fails offline verification after a key revocation.The cached JWKS lacks the replacement key, which starts signing immediately.Refetch for the unknown kid at most once a minute and reject the token if the key is still missing.
401 from GET /session/Session revoked, idle or expired, person blocked, or the MFA policy changedDeny the sensitive action. Require a fresh sign-in for an expired, idle or revoked session, enforce the current MFA policy and keep blocked accounts denied.
401 from GET /session/ after a domain switchThe token was issued under the default hostRefresh the token before calling GET /session/ again. For offline verification on your own backend, you can temporarily accept both issuers until the old tokens expire, within 5 minutes.

Key rotation, unknown kid and cache refresh

Discovery and the JWKS both answer Cache-Control: public, max-age=300, so you and shared caches keep them for 5 minutes. They allow 1,200 requests a minute and 12,000 an hour per IP address, far above the sign-in endpoints, because many backend instances often share one address.

Every key has a kid, new key IDs start with k_, and every token names its key in the kid header. We rotate keys every 30 days. We publish the next key one day before we start signing with it and keep the previous key available for one day after it stops signing, so a JWKS cached for 5 minutes keeps verifying across a rotation.

Cache keys by kid. When a token names a kid you do not have, fetch the JWKS again, at most once a minute, and reject the token if the key is still missing.

A revoked key behaves differently. When we revoke a compromised key, we remove it from the JWKS at once, and GET /session/ rejects every token that key signed. A replacement key starts signing immediately, without the day of advance publication, so a JWKS cached up to 5 minutes earlier still accepts the revoked key and does not know the replacement yet. New tokens can fail offline verification until the cache refreshes.

Activating a custom domain also changes the issuer. New tokens name it in iss, discovery points jwks_uri at it, and your publishable key changes. Access tokens issued under the default host then fail GET /session/ until they are refreshed. Update DIDIT_AUTH_ISSUER when you activate the domain. For offline verification on your own backend you can temporarily accept both issuers until the older tokens expire, within 5 minutes.

Test in the sandbox, then go live

Every Sandbox application has Authentication on from the start, accepts http://localhost callbacks and Didit's test credentials for social sign-in, and is never billed. A first sign-in with an address that has no account creates one, because the default sign-up policy lets anyone sign up.

Expected success looks like this: the sign-in button opens the hosted page, the email code arrives, the callback runs with code and state, the exchange returns the six fields above, expires_in reports the remaining access-token lifetime, up to five minutes, and 299 is an example value, verifyToken returns claims.sub and claims.vendor_data, and the sign-in appears under Authentication then Sign-ins. For the error cases, read the troubleshooting table above.

To disconnect, turn Authentication off for the application: every runtime route for that application then returns 404 until it is on again. Remove the redirect URLs and allowed origins, and stop sending people to the sign-in page. Sandbox activity is never billed, so nothing accrues while you leave the application in place.

Cost on both ends

We price Authentication per active user, not per sign-in. The first 50,000 active users each month are free, and after that allowance an active user costs $0.02 a month. The sandbox is free and unlimited on every plan, and the server SDKs, MCP server and workflow orchestrator carry no Didit fee.

Worked example at list price. 140,000 monthly active users against one 50,000-user allowance leaves 140,000 - 50,000 = 90,000 billable active users, and 90,000 x $0.02 = $1,800 a month. If those users also run exactly 20,000 completed full ID checks that month, that is 20,000 x $0.33 = $6,600 a month. Total: $1,800 + $6,600 = $8,400 a month at list price, before the Growth 4% and Scale 10% discounts that apply to every Didit price.

On your side the SDKs are free, there is no client secret to rotate, and there is no userinfo call to make: GET /session/ is the check you call instead.

Sources

Next step: create a free Sandbox application at business.didit.me, register http://localhost:3000/auth/callback, and exchange your first code. No sales call.

Try it

Try this in the sandbox

Run the check this guide describes, free.

ID Verification

The product this post is about, taken from its topic. Run it free in the sandbox.

$0.15 per checkStart free

Author

Alberto Rosas

Co-founder and CEO

Alberto Rosas

Alberto Rosas

Co-founder and CEO

About Didit

Questions

Frequently asked questions

What is the Didit Authentication token endpoint?

The Didit Authentication token endpoint is POST {issuer}/token/ on your application's sign-in origin, for example https://acme.auth.didit.me/token/. It accepts grant_type=authorization_code with the code, your PKCE verifier and the redirect URI, or grant_type=refresh_token. The body can be JSON or form-encoded, and no client secret is sent.

How long does a Didit Authentication authorization code last?

A Didit Authentication authorization code lasts 60 seconds and works once. Exchange it in the callback handler, right after you compare state with the value saved for that attempt. If the code expired or was already used, start a fresh sign-in; for any other failure, diagnose the verifier, the redirect URI, the account status and your policy settings before you start one.

How do I verify a Didit Authentication access token with JWKS?

Fetch GET {issuer}/.well-known/jwks.json, or read jwks_uri from {issuer}/.well-known/openid-configuration, and verify the ES256 signature. Then check that iss is your issuer without a trailing slash, aud is your application ID, exp is present and unexpired, the JWT header typ is at+jwt, and act is null unless the route accepts agents. All seven Didit server SDKs support Authentication token verification. The JavaScript Authentication quickstart's verifyToken helper checks the ES256 signature, issuer and expiry. Enforce the full access-token checklist before authorizing a request.

Why do I get invalid_grant when exchanging a Didit code?

Didit returns invalid_grant when the code, verifier, redirect URI or sign-in eligibility fails validation. Didit can return this error when the code is unknown, used or expired, when the verifier or the redirect URI does not match, when the person is blocked or their email is no longer verified, or when you turned off the sign-in method they used. Compare the returned state with the value you saved, exchange within 60 seconds, and compare the redirect string character by character.

How long does a Didit Authentication access token last?

A Didit Authentication access token lasts at most 5 minutes, and the response tells you the exact remainder in expires_in. The client SDK refreshes it through auth.getToken(), and the refresh token rotates on every use. Because a token stays valid until it expires, check GET {issuer}/session/ before sensitive actions.

What happens when Didit rotates signing keys?

We rotate signing keys every 30 days, and we publish the next key one day before we start signing with it and keep the previous key available for one day after it stops signing. A JWKS cached for 5 minutes therefore keeps verifying across a rotation. Cache keys by kid, and when a token names a key you do not have, fetch the JWKS again at most once a minute.

Can I verify a Didit token with my own JWT library instead of a Didit SDK?

Yes. Read the public keys from {issuer}/.well-known/jwks.json, then check the ES256 signature, the expected issuer and audience, a present and unexpired exp, the at+jwt access-token header type, and the act rule for the route. All seven Didit server SDKs support Authentication token verification. Before authorizing a request, enforce the full access-token checklist, including the route-specific act rule. Any JWT library with remote JWKS and ES256 support follows the same contract.

Do I need a client secret for Didit Authentication?

Didit Authentication uses public clients: client_id is your application ID, and PKCE with S256 protects the code exchange. The publishable key can appear in client code. Keep the Authentication secret key and verification API key off browser and mobile clients, and note that the Authentication runtime endpoints here require neither key.

Are sandbox and live tokens interchangeable?

No. Didit Authentication keeps live and sandbox apart: they are separate issuers with separate keys, separate settings and separate identities. A sandbox token fails verification against your live issuer, and a live token fails against the sandbox. Use the sandbox publishable key and the sandbox issuer while you test, then switch both variables together at go-live.

What does Didit Authentication cost?

The first 50,000 Didit Authentication active users each month are free, and after that an active user costs $0.02 a month at list price. The sandbox is free on every plan. Growth and Scale discount every Didit price by 4% and 10%.

Compliance built in

Audited, certified and attested.

We hold the certifications and build each country's rules into your flows, so you can launch anywhere without worrying. Security and Compliance center

  • Regulation encoded into your flows

    Tell us what you do and where. Didit lists the rules that apply to you, with sources, and builds the checks each country needs into one workflow.

  • Ready for AMLR

    Every requirement of the new EU anti-money laundering rules, from checking customers to human review, is already covered by a Didit check.

  • Tested in Spain's Treasury sandbox

    Spain's Treasury published its supervised sandbox report on Didit's NFC plus active liveness onboarding; SEPBLAC took part and valued the added measures positively.

  • Audited, not self-declared

    iBeta Level 1 and Level 2. Liveness tested under ISO/IEC 30107-3.

Compliance assistant

Your obligations · 3 regions

EU · AMLRCustomer due diligence, human reviewCovered
Illinois, Texas, ColoradoExplicit biometric consentCovered
Germany · Youth protectionVerified adults only (JMStV)Covered
Workflow checked. Every obligation is met
  • SOC 2 Type 2
  • ISO 27001
  • iBeta Level 1 and Level 2
  • EU regulator attestation
  • FSM youth protection
  • GDPR
  • EBA remote onboarding
  • MiCA compatible
  • FIDO Alliance member
  • AMLREU AML Regulation ready

Integration · Didit MCP

Run Didit from your own AI agent

Connect Didit to Claude, Cursor, VS Code or ChatGPT and just ask in plain words. Your agent can do anything you can do in the console, with the same permissions you have.

Add to ClaudeChatGPT
Didit Academy · Lesson 04 · Use Didit with MCP
  • Build workflowsDescribe the checks you need. The agent creates and publishes the flow.
  • Run investigationsAsk why a session was declined, review cases, search people and companies.
  • Change rulesCreate payment rules, test them on past data and switch them on.
  • Pull reportsAsk for numbers, exports or the audit log.

Verify your first user today.

Start free

Free sandbox. Credit applies to work-email sign-ups.