【问题标题】:How to share token between different routes in node js?如何在节点 js 中的不同路由之间共享令牌?
【发布时间】:2022-01-17 14:48:25
【问题描述】:

在 user.js 文件中,我使用此代码在此处创建了令牌

  if (user && bcrypt.compareSync(req.body.password, user.passwordHash)) {
    const token = jwt.sign(
      {
        userId: user.id,
        isAdmin: user.isAdmin,
      },
      process.env.SECRET,
      {
        expiresIn: "50d", // >> on day
      }
    );

令牌工作,一切正常,但我想在其他地方使用令牌,例如,在 cupon.js 文件中

router.post("/cupon", async (req, res) => {
 ...
  const token = req.header("authorization").substring(7);
 ...

我用过这个

  const token = req.header("authorization").substring(7);

从header中获取token,有没有更好的获取token的方法?

【问题讨论】:

    标签: node.js express jwt


    【解决方案1】:

    您可以为身份验证和授权创建单独的中间件。它将帮助您在任何地方或多个路由中重用它,您可以使用相同的 auth 中间件,如果在 auth 中一切正常,您可以调用 next else 发送带有401 状态码的响应。

    在 Auth.js 中

    const jwt = require('jsonwebtoken');
    
    module.exports = (req, res, next) => {
      try {
        const token = req.headers.authorization.split(' ')[1];
        const decodedToken = jwt.verify(token, 'RANDOM_TOKEN_SECRET');
        const userId = decodedToken.userId;
        if (req.body.userId && req.body.userId !== userId) {
          throw 'Invalid user ID';
        } else {
          next();
        }
      } catch {
        res.status(401).json({
          error: new Error('Invalid request!')
        });
      }
    };
    

    导入此Auth.js 并将其传递给您需要它的路线。通过这种方式,您可以对您的身份验证层进行单元测试,并可以在代码中的任何位置重用它。以下代码用于示例目的:

    const express = require('express');
    const router = express.Router();
    
    const auth = require('../middleware/auth');
    
    const stuffCtrl = require('../controllers/stuff');
    
    router.get('/', auth, stuffCtrl.getAllStuff);
    router.post('/', auth, stuffCtrl.createThing);
    router.get('/:id', auth, stuffCtrl.getOneThing);
    router.put('/:id', auth, stuffCtrl.modifyThing);
    router.delete('/:id', auth, stuffCtrl.deleteThing);
    
    module.exports = router;
    

    更多详情,您可以查看this链接并继续关注。

    【讨论】:

      猜你喜欢
      • 2021-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多