Created
December 15, 2021 21:54
-
-
Save chasers/38a842c38ee908579f21bfae9436a726 to your computer and use it in GitHub Desktop.
Cloudflare JWT decoding worker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
addEventListener("fetch", event => { | |
event.respondWith(handleRequest(event.request)) | |
}) | |
async function handleRequest(request) { | |
const token = getJwt(request) | |
const payload = get_payload(token) | |
const json = JSON.stringify(payload, null, 2) | |
return new Response(json, { | |
headers: { | |
"content-type": "application/json;charset=UTF-8" | |
} | |
}) | |
} | |
function get_payload(token) { | |
let p; | |
if (token == null) { | |
p = null; | |
} else { | |
p = decodeJwt(token); | |
} | |
return p; | |
} | |
function getJwt(request) { | |
const authHeader = request.headers.get('Authorization'); | |
if (!authHeader || authHeader.substring(0, 6) !== 'Bearer') { | |
return null | |
} | |
return authHeader.substring(6).trim() | |
} | |
function decodeJwt(token) { | |
const parts = token.split('.'); | |
const header = JSON.parse(atob(parts[0])); | |
const payload = JSON.parse(atob(parts[1])); | |
const signature = atob(parts[2].replace(/_/g, '/').replace(/-/g, '+')); | |
return { | |
payload: payload | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment