Skip to content

Instantly share code, notes, and snippets.

@wspringer
Created October 18, 2019 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wspringer/4e9ce45bf4e3fc6f972c3a659735c1e6 to your computer and use it in GitHub Desktop.
Save wspringer/4e9ce45bf4e3fc6f972c3a659735c1e6 to your computer and use it in GitHub Desktop.
import jwt from 'jsonwebtoken'
import { certToPEM } from './utils'
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function latestKeys() {
console.log('Fetching latest')
const latest = await fetch(
new Request('https://staged.eu.auth0.com/.well-known/jwks.json'),
)
return latest.json()
}
async function latestOrCached() {
const cached = await JWKS.get('keys', 'json')
if (cached) {
return cached
} else {
const latest = await latestKeys()
JWKS.put('keys', JSON.stringify(latest), { expirationTtl: 120 })
return latest
}
}
function extractToken(request) {
const auth = request.headers.get('Authorization')
const match = auth ? auth.match(/Bearer (.*)/i) : null
const token = match ? match[1] : null
return token
}
async function handleRequest(request) {
const init = {
method: request.method,
headers: request.headers,
}
const allKeys = await latestOrCached()
const token = extractToken(request)
const getKey = (header, cb) => {
const entry = allKeys.keys.find(key => key.kid === header.kid)
const cert = entry.x5c[0]
cb(
...(entry && entry.x5c
? [null, certToPEM(entry.x5c[0])]
: [new Error('failed'), null]),
)
}
return new Promise((resolve, reject) => {
if (token) {
jwt.verify(token, getKey, { algorithms: ['RS256'] }, (error, decoded) => {
if (error) {
console.log('error', error)
resolve(
new Response(`Unauthorized: ${error.message}`, { status: 401 }),
)
} else {
fetch(new Request('http://www.eastpole.nl/', init)).then(
resolve,
reject,
)
}
})
} else {
resolve(new Response('Unauthorized: missing token', { status: 401 }))
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment