skip to content

Access Policies & JWTs

Access checks identity before a request reaches an application, then passes a signed JWT the origin should verify. Interviewers ask how service tokens work and why the origin validates.

on this pageshow

explore

questions

6

Behind Cloudflare Access, how should the HR portal's origin validate Cf-Access-Jwt-Assertion, and where do its signing keys and AUD tag come from?

level: middleimportance: must knowfreq 45%

answer

  1. team domain certs endpoint
  2. match kid against both keys
  3. issuer is the team domain
  4. one AUD tag per application
  5. rotation every six weeks

basics

~20 s

Read the JWT from Cf-Access-Jwt-Assertion, verify its RS256 signature with the key whose kid matches one listed at the team domain's /cdn-cgi/access/certs, check iss is the team domain and aud holds the HR application's AUD tag, and reject expired tokens.

solid answer

~40 s

Access adds the application token to every forwarded request as `Cf-Access-Jwt-Assertion`; read the header rather than the `CF_Authorization` cookie, which is not guaranteed to be present. The token is RS256-signed with a key pair unique to the Cloudflare account, so the origin fetches the public keys from `https://<team-name>.cloudflareaccess.com/cdn-cgi/access/certs` and uses the one whose `kid` matches the token header. Access rotates that key every six weeks by default and keeps the previous one valid for seven days, which is why the endpoint lists both and why keys are never hard-coded. Then check that `iss` equals the team domain, `exp` has not passed, and `aud` contains the HR application's AUD tag, copied from its Additional settings. The `aud` check matters because the wiki's tokens are signed by the same account key.

code

javascript · 69 lines
javascript
// Verifies the Cf-Access-Jwt-Assertion header before the HR portal handles a request.
const b64url = (s) =>
  Uint8Array.from(
    atob(s.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((s.length + 3) % 4)),
    (c) => c.charCodeAt(0),
  );
const json = (s) => JSON.parse(new TextDecoder().decode(b64url(s)));

let keyCache = { fetchedAt: 0, keys: new Map() };

async function signingKey(env, kid) {
  const stale = Date.now() - keyCache.fetchedAt > 10 * 60 * 1000;
  const unknownKid = !keyCache.keys.has(kid);
  const mayRefetch = Date.now() - keyCache.fetchedAt > 30 * 1000;
  if (stale || (unknownKid && mayRefetch)) {
    const res = await fetch(`${env.TEAM_DOMAIN}/cdn-cgi/access/certs`);
    if (!res.ok) throw new Error(`certs endpoint returned ${res.status}`);
    const { keys } = await res.json(); // both the current and the previous key
    const imported = new Map();
    for (const jwk of keys) {
      imported.set(
        jwk.kid,
        await crypto.subtle.importKey(
          "jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"],
        ),
      );
    }
    keyCache = { fetchedAt: Date.now(), keys: imported };
  }
  return keyCache.keys.get(kid);
}

export async function verifyAccessJwt(token, env) {
  const parts = token.split(".");
  if (parts.length !== 3) throw new Error("malformed token");
  const [h, p, s] = parts;
  const header = json(h);
  if (header.alg !== "RS256") throw new Error("unexpected alg");
  const key = await signingKey(env, header.kid);
  if (!key) throw new Error("unknown kid");
  const valid = await crypto.subtle.verify(
    "RSASSA-PKCS1-v1_5", key, b64url(s), new TextEncoder().encode(`${h}.${p}`),
  );
  if (!valid) throw new Error("bad signature");
  const claims = json(p);
  const now = Math.floor(Date.now() / 1000);
  if (claims.iss !== env.TEAM_DOMAIN) throw new Error("wrong issuer");
  const aud = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
  if (!aud.includes(env.POLICY_AUD)) throw new Error("wrong audience");
  if (typeof claims.exp !== "number" || claims.exp < now) throw new Error("expired");
  if (typeof claims.nbf === "number" && claims.nbf > now + 30) throw new Error("not yet valid");
  return claims;
}

export default {
  async fetch(request, env) {
    const token = request.headers.get("Cf-Access-Jwt-Assertion");
    if (!token) return new Response("Forbidden", { status: 403 });
    try {
      const claims = await verifyAccessJwt(token, env);
      // A service token's JWT has an empty sub and carries the Client ID in common_name.
      const caller = claims.email ?? `service:${claims.common_name}`;
      return new Response(`hello ${caller}`);
    } catch (err) {
      console.log(`Access JWT rejected: ${err.message}`);
      return new Response("Forbidden", { status: 403 });
    }
  },
};

go deeper

for a junior

Recall the header name, the certs URL on the team domain and the three claims to check: iss, aud and exp. Know that decoding is not verifying.

for a middle

Explain the six-week rotation with a seven-day overlap, matching kid rather than reading public_cert, and where the AUD tag comes from and why it stays fixed.

for a senior

Explain why the account-wide signing key makes the aud check the barrier between applications, and when cloudflared's Protect with Access can do the check for you.

for a principal

Make verification a shared library or edge component every origin uses, with the AUD tag in configuration and get-identity for group-based authorisation.

## What arrives at the origin When Access forwards a request, it adds the **application token**, a JWT, in the `Cf-Access-Jwt-Assertion` request header. Browser requests also carry it as the `CF_Authorization` cookie, but the cookie is not guaranteed to be passed, so the header is the source to read. Cloudflare signs the token with **RS256** using a key pair unique to the account. The origin's job is to prove the token came from Access, for this application, and is still valid. ## Where the keys come from The public keys live on the team domain at `https://<team-name>.cloudflareaccess.com/cdn-cgi/access/certs`. The response holds: - `keys`: the current and the previous signing key, in JWK format; - `public_cert`: the current key only, in PEM format; - `public_certs`: both keys in PEM format. By default **Access rotates the signing key every six weeks**, and the previous key stays valid for **seven days** after rotation; an administrator can also rotate it through the API. Two rules follow from that: - Fetch keys from the endpoint and cache them; do not paste a key into configuration, which breaks at the next rotation. - Do not read `public_cert` as "the key". A stale cache can hold an outdated value; match the token's `kid` against the entries in `keys` or `public_certs` instead, and refetch when a `kid` is unknown. ## The checks, in Cloudflare's terms 1. The `Cf-Access-Jwt-Assertion` header is present; if not, reject with 403. 2. The header's `alg` is `RS256` and its `kid` names a key from the certs endpoint. 3. The signature over the header and payload verifies with that key. 4. `iss` equals the team domain, `https://<team-name>.cloudflareaccess.com`. 5. `aud` contains the HR application's **AUD tag**. 6. `exp` has not passed, and `nbf` is not in the future. Only after all six does the origin read claims such as `email`. Decoding the payload without step 3 proves nothing, since anyone can write a JWT-shaped string. ## Why the AUD tag is not optional Every Access application gets its own **Application Audience (AUD) Tag**, found under the application's **Additional settings**. It never changes unless the application is deleted and recreated, so it is safe to store in the origin's configuration, with a note to update it if the application is ever rebuilt. The signing key, by contrast, is shared across the whole account. A token Access issued for the company wiki has a valid signature and the right issuer. If the HR origin checked only signature and issuer, an employee with wiki access who could reach the HR origin some other way could present a wiki token and be accepted. Only the `aud` check against the HR application's tag separates the two. | Claim | User token | Service token | |---|---|---| | `aud` | AUD tag of the application | AUD tag of the application | | `iss` | Team domain | Team domain | | `email` | Verified email from the identity provider | Absent | | `sub` | The user's ID | Empty string | | `common_name` | Absent | The service token's Client ID | ## Letting cloudflared check instead When the portal is published through Cloudflare Tunnel, `cloudflared` can do the validation before proxying: the tunnel's **Protect with Access** setting, or an `access` block under `originRequest` in a locally managed configuration with `required: true`, the `teamName` and the application's `audTag` values. That covers requests arriving through the tunnel; an origin that also listens elsewhere still needs its own check. The same holds when the protected application is itself a Worker: Access in front of it does not excuse the Worker from validating the token it receives, which is exactly what the code example does. ## Identity after validation - Take the user from the verified claims, not from the plain `Cf-Access-Authenticated-User-Email` header. - Groups appear in the token only when configured as a custom SAML attribute or OIDC claim, and Access trims custom claims once they exceed about 1 KB, starting with values at the end of the list. For authorisation by group, send the `CF_Authorization` cookie to the team domain's `/cdn-cgi/access/get-identity` endpoint to get the full identity. - For the nightly job, authorise by `common_name` rather than by an email it does not have. The code example shows the checks in a Worker in front of the HR portal, using Web Crypto, so it needs no library.

  • Why not save the key from `public_cert` in the origin's configuration?
    Access rotates its signing key every six weeks by default and honours the previous key for only seven days, so a saved key fails within weeks, and `public_cert` read from a stale cache can already be outdated. Match the token's `kid` against the keys the certs endpoint lists and refetch when a `kid` is unknown.
  • How does the HR origin tell the nightly job from an employee?
    A service-token JWT has an empty `sub`, no `email`, and the service token's Client ID in `common_name`. The origin can serve the export only when `common_name` equals the job's Client ID, and serve employee pages only when a verified `email` is present.
  • Where should the HR portal get an employee's groups?
    From the team domain's `/cdn-cgi/access/get-identity` endpoint, called with the `CF_Authorization` cookie. Groups reach the JWT only when configured as a custom claim, and Access trims custom claims above about 1 KB, so a user in many groups can arrive without them.

  • Decoding the JWT and reading email is enough, because Access already checked it.
  • Any token signed by our account's key is fine for any of our applications.
  • Paste the PEM from public_cert into config so the origin never calls the certs endpoint.
  • The CF_Authorization cookie is the more reliable place to read the token.
  • The AUD tag changes whenever Access rotates its signing key.
open as a page

In Cloudflare Access, how do the Allow, Block, Bypass and Service Auth actions differ, and in what order are an application's policies evaluated?

level: middleimportance: must knowfreq 45%

basics

~20 s

Allow admits matching users, Block refuses them, Bypass switches Access off for matching traffic without logging it, and Service Auth admits service tokens or client certificates without an identity provider login. Bypass and Service Auth run first, then Allow and Block in order.

open as a page

With Cloudflare Access, how does a nightly reporting job with no browser authenticate to one HR endpoint using a service token?

level: middleimportance: must knowfreq 40%

basics

~20 s

Create a service token, attach a Service Auth policy with the Service Token selector to an Access application for that endpoint, and have the job send CF-Access-Client-Id and CF-Access-Client-Secret headers; Access then forwards a JWT whose common_name is the Client ID.

open as a page

In Cloudflare Access, what happens when an employee first opens the company wiki, and what reaches the wiki's origin afterwards?

level: juniorimportance: should knowfreq 35%

basics

~20 s

Access stops the request, sends the employee to the team domain's login page to sign in through an identity provider, checks the application's policies, then sets CF_Authorization cookies and forwards each request with a signed JWT in Cf-Access-Jwt-Assertion.

open as a page

An HR portal behind Cloudflare Access trusted every request that reached it, and an audit found requests that never passed Access; how did they arrive, and what closes each path?

level: seniorimportance: should knowfreq 40%

basics

~20 s

They reached the origin directly by IP, or through a hostname, path or Bypass policy no Access application enforced, and the origin trusted headers instead of the JWT. Verify Cf-Access-Jwt-Assertion against the HR AUD tag, then close each route.

open as a page

As the lead replacing a VPN with Cloudflare Access for a wiki and an HR portal, which account rules and session durations do you set, and what must each origin still check?

level: principalimportance: should knowfreq 30%

basics

~20 s

Give each application its own policies and AUD tag, keep HR sessions short and the wiki's longer, turn on Block traffic to all domains in this account and strict service token authentication, review every Bypass, and make each origin verify the Access JWT.

open as a page