# JWT Verification best practise

{% hint style="success" %}
We advise following best practise when leveraging JWT Verification. In doing so, this also allows us to rotate the KMS keys which in-turn helps us to increase the resilience of our SaaS platform (Active/active implementations etc.).
{% endhint %}

### Where to download the Keyless `jwks.json` endpoint

The Keyless endpoint for downloading the `jwks.json` is available at <https://api.keyless.io/customers/keyless/.well-known/jwks.json>

{% hint style="info" %}
Note in this example we have used api.keyless.io as the Operation Service URL and "keyless" as the customer name. Replace this customer name with the tenant name you were provided nad the correct Operation Service URL for your region as listed [here](https://docs.keyless.io/consumer/server-api/getting-started#latam).
{% endhint %}

### The Verification Process

1. **Extract the Header:** Parse the JWT header (unverified) to retrieve the `kid` (Key ID) and `alg` (Algorithm) parameters.
2. **Lookup the Key:** \* Search the cached `jwks.json` for a key where the `kid` matches the JWT header. Confirm the `use` property is `sig` (signature) and the `alg` matches your expected security profile (e.g., `RS256`).
3. **Construct Public Key:** Convert the JWK components (for RSA: the `n` modulus and `e` exponent) into a PEM-formatted public key.
4. **Validate Signature:** Use the reconstructed public key to verify the JWT's cryptographic signature and check standard claims (`exp`, `iat`, `iss`).

### Handling Key rotation

To prevent authentication failures when keys are rotated, implement the following logic in your validation logic:

1. **Caching with Refresh:** Maintain an in-memory cache of the JWKS. Set a standard TTL (e.g., 24 hours).
2. **Lazy Refresh on `kid` Mismatch:** If a JWT arrives with a `kid` not present in your current cache, perform an immediate, one-time fetch of the `jwks.json` to see if a new key has been published.
3. **Rate Limiting:** Limit "on-demand" JWKS fetches (e.g., once every 5 minutes) to prevent a malicious actor from triggering a Denial of Service (DoS) by sending tokens with random `kid` values.
4. **Graceful Overlap:** Ensure your verification logic can handle multiple keys in the `keys` array simultaneously. During rotation, the provider will publish both the old and new keys; your system should trust any valid key currently present in the set.
