Policies-based authentication for Fresh.
- create a middleware to add user information to the context
const authMiddleware = createAuthMiddleware<string, string>(async (ctx) => {
const accessToken = ctx.req.headers.get("Authorization")?.slice(7);
if (!accessToken) return undefined;
const { error, result } = await mightFail(verifyToken(accessToken))
return error ? undefined : { id: result.payload.sub!, policies: result.payload.policies as string[] };
});
- create a handler with policies
app.get("/user", defineHandler((ctx) => {
return new Response(`Here is ${getAuthInfo(ctx)?.id}.`)
}, ["user"]) as MiddlewareFn<unknown>);