# Key rotation

Cryptographic keys published by BankID are used to ensure the authenticity and integrity of issued JWT tokens,
and to encrypt sensitive data from merchant to the provider.

These keys are published in the [JWKs](https://docs.stoe.no/bankid-oidc-provider/api/jwks.md) endpoint in the [JWK](https://openid.net/specs/draft-jones-json-web-key-03.html)
format. These keys may change regularly, so make sure you keep them up-to-date (every 24 hours).

## Our responsibility

To make key management as smooth as possible:

- we will always publish new keys before they are used
- old keys will be available to verify tokens some time after rotating out
- have cache-control header in JWKs endpoint with a max-age (seconds) which defines the minimum guaranteed life time of all the keys returned.
  - Header value example: cache-control: public, max-age=23269, must-revalidate, no-transform

## Your responsibility

> **Always verify**
>
> Always verify the signatures and signing keys of Tokens issued by BankID.

When handling keys from our [JWKs](https://docs.stoe.no/bankid-oidc-provider/api/jwks.md) endpoint:

- Cache all keys returned from `jwks_uri` and `jwks_uri_enc`, as several may be in use
- Refresh keys at intervals, but not on every request, to avoid possible DDOS attacks when key is unknown.
- Take advantage of the `max-age` value returned in `cache-control` header.

When validating tokens or JWTs, find key using a combination of claims `kid`, `alg` and `use`.

When encrypting JWTs, select key to use by `kty`, `use` and `alg` claims.

## Rotation of keys

We may publish three `sig`/`enc` keys for each algorithm. Every key will always have a unique `kid` value.

1. the next key,
2. the currently used key
3. the previously used key.

Cache header will have `max-age` set to time between rotations (minus some minutes).

When rotating, current replaces previous key, next replaces current, a new one will be
introduced and the oldest one will be discarded.

Remember, the merchant is responsible to keep keys up-to-date regularly.
