How do I get JWT to work with Koa?

So here is my current code…

    import jwt from "koa-jwt";
    this.whitelist = [
        /^\/callback/,
        /^\/ping/
    ];
    this.jwt = jwt({
        cookie: "Authorization",
        secret: AUTH_SECRET
    }).unless({ path: this.whitelist })

    this.app.use((ctx, next)=>{
        return next().catch((err) => {
            console.log("Errored out "+err);
            console.log("Cookie is "+ctx.cookies.get("Authorization"));
            if (401 == err.status) {
                ctx.redirect(`https:\/\/${AUTH_DOMAIN}/authorize?response_type=code&client_id=${AUTH_CLIENT_ID}&redirect_uri=${AUTH_REDIRECT}`)
            } else {
               throw err;
            }
        });
    });
    this.app.use(this.jwt);

Then I set the access token as the cookie…

ctx.cookies.set("Authorization", response.data.access_token, {httpOnly: false})

But when I try to run this it always says the token is invalid (even though it looks correct in console). I tried both the access and id tokens. Can anyone help?

Here was my final solution…

    import jwt from "koa-jwt";
    import jwtrsa from 'jwks-rsa';
    ....
    this.whitelist = [
        /^\/callback/,
        /^\/ping$/,
        "/",
        /^\/ui/,
        /^\/vue/,
    ];

    this.jwt = jwt({
        secret: jwtrsa.koaJwtSecret({
            jwksUri: `https:\/\/${AUTH_DOMAIN}/.well-known/jwks.json`,
            cache: true,
            cacheMaxEntries: 5
        }),
        audience: AUTH_CLIENT_ID,
        issuer: `https:\/\/${AUTH_DOMAIN}/`,
        cookie: "Authorization"
    }).unless({ path: this.whitelist })
    this.app.use(this.jwt);
1 Like

Thanks a lot @jackiegleason for sharing it with rest of community!