【问题标题】:How to set a jwt cookie with mocha/chai?如何使用 mocha/chai 设置 jwt cookie?
【发布时间】:2021-07-01 08:48:43
【问题描述】:

我需要用 mocha 和 chai 测试受保护的路线。由于jwt must be a string,身份验证中间件一直崩溃并出现错误500。

当用户登录时,他会收到一个 http-only cookie,其数据是一个 jwt 令牌。由于 axios withCredentials: true 属性,cookie 会在每次请求时自动发送到服务器。

所以,我尝试为我的测试设置一个 cookie 或一个身份验证承载,但到目前为止没有任何成功。如何解决这个问题?

这是我写的:

import chai from "chai";
import chaiHttp from "chai-http";
import { app } from "../index";
import jwt from "jsonwebtoken";

chai.use(chaiHttp);
const api = chai.request(app).keepOpen();
const token = jwt.sign(
  { _id: "123", locale: "en" },
  process.env.JWT_TOKEN_KEY,
  {
    expiresIn: "14d",
  }
);

describe("GET /user/:id", () => {
  it("return user information", (done) => {
    api
      .get("/user/123")
      .set("Cookie", token)
      .end((err, res) => {
        chai.expect(res).to.have.status(200);
        done();
      });
  });
});

中间件是:

import { Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";
import { Cookie } from "../models/Cookie";

interface Authenticate extends Request {
  cookie: Cookie;
  cookies: any;
}

const authenticate = (req: Authenticate, res: Response, next: NextFunction) => {
  const token = req.cookies; 
  if (token) {
    jwt.verify(token, process.env.JWT_TOKEN_KEY, (error, res) => {
      if (error) {
        return res.sendStatus(403);
      }
      req.cookie = { _id: res._id, locale: res.locale };
      return next();
    });
  }
  return res.sendStatus(401);
};

export default authenticate;

自 48 小时以来,我一直在测试我的 api 路由。任何帮助将不胜感激。

【问题讨论】:

    标签: node.js jwt mocha.js chai


    【解决方案1】:

    req.cookies是一个对象,来自express docs:

    当使用 cookie-parser 中间件时,该属性是一个包含请求发送的 cookie 的对象。如果请求不包含 cookie,则默认为 {}。

    所以你需要这样设置cookie里面的jwt:

    .set('Cookie', `jwtToken=${token}`)
    

    并在您的中间件中获取它:

    const { jwtToken } = req.cookies;
    jwt.verify(jwtToken, ...
    

    【讨论】:

      猜你喜欢
      • 2020-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-14
      • 1970-01-01
      • 2017-06-05
      • 1970-01-01
      • 2016-05-19
      相关资源
      最近更新 更多