Example Cloudflare worker to decode and validate Cloudflare Access JWT tokens.
Depends on @tsndr/cloudflare-worker-jwt
The code fetches public keys from https://${env.ACCESS_TEAM_NAME}.cloudflareaccess.com/cdn-cgi/access/certs
. Your team name can be found in the Custom Pages settings of the Cloudflare Zero Trust dashboard.
To avoid making a fetch request on the certs endpoint for every JWT validation, public keys are cached in a worker secret CLOUDFLARE_ACCESS_PUBLIC_KEYS. A query parameter of f=1
will force this value to be refreshed. (TODO force a refresh with a weekly cron worker)
By decoding the JWT from the CF_Authorization
cookie instead of relying on the cf-access-jwt-assertion
header, you can continue identifying authenticated users even for un-authed routes on the same origin, once they have logged in. This works because the cookie is scoped to the hostname unless you explicitly configure Access to scope the cookie to the application path.
Originally motivated by this thread by Adam Janiš.
Alternative implementation using hono middleware and jose.
- Run
pnpm install
andpnpm ship
(using 'ship' instead of 'deploy' allows 'pnpm ship' without 'run') - Set the necessary secrets using
pnpm wrangler secret put <SECRET_NAME>
See wrangler.toml for details. - Configure the deployed worker to trigger on your endpoint.
- Open the endpoint and authenticate with your browser.
- Tests
- TypeScript
- Mock jwt and keys for local use