Skip to content

Instantly share code, notes, and snippets.

@eidam
Last active August 14, 2024 07:35
Show Gist options
  • Save eidam/7fb298196a43b2c172245219c6dd7da1 to your computer and use it in GitHub Desktop.
Save eidam/7fb298196a43b2c172245219c6dd7da1 to your computer and use it in GitHub Desktop.
Workers Hono Access Middleware
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