Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 37 ยท Projects and Practice

Project: A JWT Verifier for Your API

Build a token verifier for a resource server: fetch JWKS, verify RS256 signatures, check iss, aud, exp and roles, with a runnable example using WebCrypto and a generated key.

Your API receives a bearer token from a client and must decide whether to trust it. In this project you build the verification logic yourself so you understand each check: signature, issuer, audience, expiry, and finally roles. Keycloak access tokens are JWTs signed with RS256 by default; the public keys are published at the realm's JWKS endpoint: https://auth.example.com/realms/<realm>/protocol/openid-connect/certs.

Keycloak cannot run on this site, so the example generates its own RSA key pair and signs a test token to play the role of Keycloak. The verifier logic is the real pattern, but in production use a maintained JWT library for your language and cache the JWKS. Never write your own crypto for a real service.

What to verify

A token is trustworthy only if all of these hold:

  1. Structure: three base64url parts: header, payload, signature.
  2. Algorithm: the header's alg is one you expect (RS256). Never accept none, and never let the token choose a weaker algorithm than your configuration.
  3. Signature: valid for the key identified by the header's kid, found in the JWKS.
  4. Issuer (iss): exactly https://auth.example.com/realms/<realm>.
  5. Audience (aud): contains your API's client ID. (See protocol mappers to add it.)
  6. Time: exp is in the future; nbf (if present) in the past; allow a small clock skew.
  7. Authorization: required roles or scopes are present, in realm_access.roles, resource_access.<client>.roles, or scope.

Also consider the authorized party azp (which client the token was issued to) and, for sensitive operations, token revocation checks via introspection.

flowchart TD
  T["Bearer token"] --> P["Parse header.payload.signature"]
  P --> A{"alg allowed?"}
  A -->|"no"| X["401"]
  A -->|"yes"| K["Find key by kid in JWKS"]
  K --> S{"Signature valid?"}
  S -->|"no"| X
  S -->|"yes"| C{"iss, aud, exp ok?"}
  C -->|"no"| X
  C -->|"yes"| R{"Required role present?"}
  R -->|"no"| F["403"]
  R -->|"yes"| OK["Proceed"]

401 means "not authenticated"; 403 means "authenticated but not allowed".

The verifier

This runnable example generates a key, publishes it as a JWKS, signs tokens, and verifies them with WebCrypto, which exists in browsers and Node.

JS RS256 verifier with JWKS, claims and roles

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Read the results: the signed-but-wrong tokens are rejected for the right reason, the alg: none token is refused before any key is looked up, and a missing role produces 403 rather than 401.

JWKS handling in production

  • Fetch the JWKS from the realm's certs URL over HTTPS. Pin the issuer; do not take a jku or JWKS URL from the token itself.
  • Cache keys with a sensible TTL (minutes to hours). When a token's kid is unknown, refetch once (rate-limited) to pick up a key rotation, then fail.
  • Support rotation: Keycloak keeps old keys for verification while new ones sign, so multiple keys appear in the set.
  • Algorithm: pin RS256 (or whatever your realm uses under Realm settings > Keys).

Opaque tokens and introspection

Local verification cannot see revocation: a token stays valid until exp. For high-risk operations call the introspection endpoint (/protocol/openid-connect/token/introspect) with your API's client credentials. Use short token lifetimes (5 minutes is a common default for access tokens) to limit the window.

Mapping roles to permissions

Keep the role names in one place and test them. For example:

Route Required role
GET /invoices invoice-viewer
POST /invoices invoice-editor
DELETE /invoices/{id} invoice-admin

For rules that depend on the specific invoice, move to Authorization Services or enforce ownership in code using the sub claim.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A token is correctly signed but its aud does not include your API. What should happen?

    Audience checks stop tokens issued for other services from being replayed against yours.
  2. 2. Where does the API find the public key to verify the signature?

    Keycloak publishes public keys at the certs endpoint, and the kid selects the right one.
  3. 3. When is 403 the correct status?

    403 means authenticated but not authorized; invalid or missing credentials are 401.
  4. 4. Why must the verifier pin the expected algorithm?

    Letting the token choose its own algorithm has led to real vulnerabilities.

Summary

  • Verify structure, algorithm, signature, issuer, audience, expiry, then roles.
  • Use the realm JWKS, cached, with refetch on unknown kid.
  • 401 for bad credentials, 403 for missing permission.
  • Use a maintained library in production; add introspection for revocation-sensitive actions.

Next: Project: Designing a Multi-Tenant Setup