【问题标题】:Passing jwt token/userid from `app.post()` to the `app.get()` route将 jwt 令牌/用户 ID 从 `app.post()` 传递到 `app.get()` 路由
【发布时间】:2021-09-11 07:15:33
【问题描述】:

这是我的app.post(),它从客户端获取表单数据。

app.post('/api/login', async (req, res) => {
  const { emailid, password } = req.body
  const user = await User.findOne({ emailid }).lean()

  if (!user) {
    return res.json({ status: 'error', error: " Invalid username/Password" })
  }
  if (bcrypt.compare(password, user.password)) {
    const token = jwt.sign({ id: user._id, emailid: user.emailid }, 'secret', { expiresIn: '24h' })
    return res.json({ status: 'ok', data: token, user_id: user._id })
  }
  res.json({ status: 'error', error: " Invalid username/Password" })
})

我需要将jwt 令牌或user_id 传递给我的

app.get('/', (req,res)=>{
  res.render('index')
})

【问题讨论】:

  • /api/login 路由只会执行一次,但我认为后续的几个请求都需要 JWT。因此,您必须将令牌发送回客户端,然后客户端必须在每个后续请求中包含它(作为Authorization: Bearer <JWT> 标头)。另见auth0.com/docs/authorization/flows/authorization-code-flow。因此,实际上是客户端在做“令牌传递”。

标签: node.js mongodb express middleware


【解决方案1】:

为此,您需要创建一个身份验证中间件,该中间件将检查您的请求标头中的 jwt token,然后您可以对其进行解码以获取 user_id 或您在加密期间传递给它的任何其他数据。示例中间件如下所示

const isAuth = (req) => {
  const authorization = req.headers["authorization"];
  if (!authorization) throw new Error("You need to log in");
  const token = authorization.split(" ")[1];
  const { user_id} = verify(token, process.env.ACCESS_TOKEN_SECRET);
  return {user_id, token};
};

设置授权中间件后,您可以继续在您的路由中使用它

app.get('/', (req,res)=>{
const {token, user_id) = isAuth(req);
    //use token and user_id here or throw error if not available in case this is a protected route
  res.render('index')
})

【讨论】:

  • 但是如何在标头中传递 jwt 令牌?
  • @KaartikNayak 你准备好客户端还是使用邮递员进行测试?
  • 基本上客户端只是一个发送post req到/api/login的表单
  • 您使用的是框架还是只使用 Javascript、HTML 和 CSS?
  • ejs表达
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-24
  • 2021-08-20
  • 2019-09-21
  • 2019-11-13
  • 2019-09-10
  • 2020-01-31
  • 2020-05-05
相关资源
最近更新 更多