Cloudflare Workers Access
Authenticate with Cloudflare Access from within a Cloudflare Worker.
Installation
npm install --save @matthewgall/cfaccess-jwt
Usage
import { CFAccess } from "@matthewgall/cfaccess-jwt";
const AUTHENTICATION_DOMAIN = "matthewgall.cloudflareaccess.com";
const POLICY_AUD = "9607121bab7ceeed691bc06782b5030c7e054a27e3f98467b79f97a5f3708112";
async handleRequest(request) {
// We are going to enforce Cloudflare Access
let access = new CFAccess(AUTHENTICATION_DOMAIN, POLICY_AUD)
access = await access.validate(request)
if (access['valid']) {
output = {
"success": true,
}
}
else {
output = {
"success": false,
}
}
return new Response(JSON.stringify(output, null, 2), {
status: 403,
headers: Headers
})
}
addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event.request));
});
CFAccess
takes two parameters:
-
The team domain, provided when you signed up for Cloudflare Teams: https://developers.cloudflare.com/cloudflare-one/setup#set-up-cloudflare-access
-
Optionally, two further parameters
-
aud
: The "Audience Tag" of your Access Policy. -
tolerance
: Number of seconds of leeway for validatingexp
andnbf
claims. Defaults to0
.
-
When you're ready to check, call the validate() function with either a request
object or a JWT string. This will return a Promise and eventually an object:
-
Promise.valid
will contain the status of the JWT -
Promise.message
will contain any reasons for failure to validate