Skip to content

Commit f739052

Browse files
irvinebroqueranbel
andauthored
Add example for validating JWT in a Cloudflare Worker (#25360)
* Add example for validating JWT in a Cloudflare Worker * PCX edits --------- Co-authored-by: ranbel <[email protected]>
1 parent 4044d74 commit f739052

File tree

1 file changed

+57
-5
lines changed

1 file changed

+57
-5
lines changed

src/content/docs/cloudflare-one/identity/authorization-cookie/validating-json.mdx

Lines changed: 57 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,62 @@ To get the AUD tag:
102102

103103
You can now paste the AUD tag into your token validation script. The AUD tag will never change unless you delete or recreate the Access application.
104104

105+
### Cloudflare Workers example
106+
107+
When Cloudflare Access is in front of your [Worker](/workers), your Worker still needs to validate the JWT that Cloudflare Access adds to the `Cf-Access-Jwt-Assertion` header on the incoming request.
108+
109+
The following code will validate the JWT using the [jose NPM package](https://www.npmjs.com/package/jose):
110+
111+
```javascript
112+
import { jwtVerify, createRemoteJWKSet } from 'jose';
113+
114+
export default {
115+
async fetch(request, env, ctx) {
116+
// Get the JWT from the request headers
117+
const token = request.headers.get('cf-access-jwt-assertion');
118+
119+
// Check if token exists
120+
if (!token) {
121+
return new Response('Missing required CF Access JWT', {
122+
status: 403,
123+
headers: { 'Content-Type': 'text/plain' }
124+
});
125+
}
126+
127+
try {
128+
// Create JWKS from your team domain
129+
const JWKS = createRemoteJWKSet(new URL(`${env.TEAM_DOMAIN}/cdn-cgi/access/certs`));
130+
131+
// Verify the JWT
132+
const { payload } = await jwtVerify(token, JWKS, {
133+
issuer: env.TEAM_DOMAIN,
134+
audience: env.POLICY_AUD,
135+
});
136+
137+
// Token is valid, proceed with your application logic
138+
return new Response(`Hello ${payload.email || 'authenticated user'}!`, {
139+
headers: { 'Content-Type': 'text/plain' }
140+
});
141+
142+
} catch (error) {
143+
// Token verification failed
144+
return new Response(`Invalid token: ${error.message}`, {
145+
status: 403,
146+
headers: { 'Content-Type': 'text/plain' }
147+
});
148+
}
149+
},
150+
};
151+
```
152+
153+
#### Required environment variables
154+
155+
Add these [environment variables](/workers/configuration/environment-variables/) to your Worker:
156+
- `POLICY_AUD`: Your application's [AUD tag](#get-your-aud-tag)
157+
- `TEAM_DOMAIN`: `https://<your-team-name>.cloudflareaccess.com`, where `<your-team-name>` is replaced with your actual <GlossaryTooltip term="team name">team name</GlossaryTooltip>.
158+
159+
You can set these variables by adding them to your Worker's [Wrangler configuration file](/workers/wrangler/configuration/), or via the Cloudflare dashboard under **Workers & Pages** > **your-worker** > **Settings** > **Environment Variables**.
160+
105161
### Golang example
106162

107163
```go
@@ -246,7 +302,7 @@ if __name__ == '__main__':
246302
app.run()
247303
```
248304

249-
### JavaScript example
305+
### JavaScript (Node.js) example
250306

251307
```javascript
252308
const express = require("express");
@@ -292,7 +348,3 @@ app.get("/", (req, res) => {
292348

293349
app.listen(3333);
294350
```
295-
296-
## Related resources
297-
298-
- [Verifying JWTs in Cloudflare Workers](https://kinde.com/blog/engineering/verifying-jwts-in-cloudflare-workers/) - Implement JWT verification in Cloudflare Workers.

0 commit comments

Comments
 (0)