0

I'm trying to create a middleware in Deno using oak, I want to validate a jwt token and then if everything is OK add the payload to the request body.

Found this code:

import { validateJwt } from "https://deno.land/x/djwt/validate.ts"
import { key } from "../utils/jwt.js";

export const validate = async ({request, cookies}, next) => {
    const token = await cookies.get("token");
    const result = await validateJwt(token, key, { isThrowing: false });
    if(result) {
        request.auth = true;
        request.username = result.payload.username;
    }
    await next();
}

but is not working any more and haven't been able to find anything about how to add properties to the request.

What I want to achieve at the end is to access the payload inside the controller.

Thanks in advance. Any guidance will be much appreciated

  • the code above is outdated and based on an early version of djwt. My answer [here](https://stackoverflow.com/questions/64494966/jwt-authentication-with-deno/64496661#64496661) is up to date and shows how to sign and verify a JWT in Deno. – jps Apr 08 '21 at 07:55
  • thanks for the answer, I have the jwt verification sorted. Mine is a OAK question, I want to pass the jwt payload to the request using a middleware – Adrian Sanchez Apr 08 '21 at 16:24

1 Answers1

0

Took a while but found how to do it. To pass a variable from a middleware to the route or another middleware you don't use the Request anymore but instead you use the context State

app.use(async (ctx, next) => {
  // do whatever checks to determine the user ID
  ctx.state.userId = userId;
  await next();
  delete ctx.state.userId; // cleanup
});

app.use(async (ctx, next) => {
  // now the state.userId will be set for the rest of the middleware
  ctx.state.userId;
  await next();
});