Last active
August 14, 2024 07:35
-
-
Save eidam/7fb298196a43b2c172245219c6dd7da1 to your computer and use it in GitHub Desktop.
Workers Hono Access Middleware
This file contains hidden or 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
import { createMiddleware } from 'hono/factory'; | |
import { HonoEnv } from '../routers/api'; | |
import * as jose from 'jose'; | |
const zeroTrustAccount = "<account-name>" | |
const zeroTrustAppAud = "<application-audience>" | |
const JWKS = jose.createRemoteJWKSet(new URL(`https://${zeroTrustAccount}.cloudflareaccess.com/cdn-cgi/access/certs`)); | |
export const cloudflareAccess = createMiddleware<HonoEnv>(async (c, next) => { | |
const jwt = c.req.header('cf-access-jwt-assertion'); | |
if (!jwt) { | |
return c.json({ error: 'Unauthorized (missing jwt header)' }, 401); | |
} | |
try { | |
const { payload } = await jose.jwtVerify<{ email: string }>(jwt, JWKS, { | |
issuer: `https://${zeroTrustAccount}.cloudflareaccess.com`, | |
audience: zeroTrustAppAud, | |
}); | |
c.set('user', { email: payload.email }); | |
await next(); | |
} catch (e) { | |
return c.json({ error: 'Unauthorized' }, 401); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment