【问题标题】:Deno middleware to add payload to requestDeno 中间件向请求添加有效负载
【发布时间】:2021-04-09 11:04:29
【问题描述】:

我正在尝试使用 Oak 在 Deno 中创建一个中间件,我想验证一个 jwt 令牌,然后如果一切正常,则将有效负载添加到请求正文中。

找到这个代码:

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();
}

但不再工作,并且无法找到有关如何向请求添加属性的任何信息。

我最后想要实现的是访问控制器内部的有效负载。

提前致谢。任何指导将不胜感激

【问题讨论】:

  • 上面的代码已经过时并且基于早期版本的 djwt。我的回答 here 是最新的,它展示了如何在 Deno 中签名和验证 JWT。
  • 感谢您的回答,我已对 jwt 验证进行了排序。我的是一个 OAK 问题,我想使用中间件将 jwt 有效负载传递给请求

标签: deno oak


【解决方案1】:

花了一段时间,但找到了方法。要将变量从中间件传递到路由或其他中间件,您不再使用请求,而是使用上下文状态

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();
});

【讨论】:

    猜你喜欢
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    • 1970-01-01
    • 2017-02-22
    相关资源
    最近更新 更多