H
Hono3w ago
Zachary

Many JWT Middlewares OR-ed together

Hi, I have a set of legal JWT keys. I'd like any one of them to allow a request through the middleware. This works:
export default function orCombinator<
E extends HonoEnv = any,
P extends string = string,
I extends Input = {},
>(
handlers: Array<MiddlewareHandler<E, P, I>>,
onFail: (c: Context<E, P, I>) => Response,
): (c: Context<E, P, I>, next: Next) => Promise<Response | void> {
return async (c, next) => {
if (handlers.length == 0) {
return onFail(c);
} else {
const handler = handlers[0];
try {
return await handler(c, next);
} catch {
return orCombinator(handlers.slice(1), onFail)(c, next);
}
}
};
}

...
orCombinator([jwt({secret: "bizfoobar"}), jwt({secret: "foobarbaz"})], c => c.text("no can do"))
export default function orCombinator<
E extends HonoEnv = any,
P extends string = string,
I extends Input = {},
>(
handlers: Array<MiddlewareHandler<E, P, I>>,
onFail: (c: Context<E, P, I>) => Response,
): (c: Context<E, P, I>, next: Next) => Promise<Response | void> {
return async (c, next) => {
if (handlers.length == 0) {
return onFail(c);
} else {
const handler = handlers[0];
try {
return await handler(c, next);
} catch {
return orCombinator(handlers.slice(1), onFail)(c, next);
}
}
};
}

...
orCombinator([jwt({secret: "bizfoobar"}), jwt({secret: "foobarbaz"})], c => c.text("no can do"))
Is there a supported mechanism for this?
3 Replies
Zachary
ZacharyOP3w ago
that's exactly what I need. thanks! Hm, is there any way to provide the response to produce on a failed validation?
ambergristle
ambergristle3w ago
i've never used it. i'd expect uncaught errors to be handled by app.onError. otherwise, it will keep calling middleware until it runs out, or one of them returns true

Did you find this page helpful?