【问题标题】:Basic authentication and passing token to next endpoint基本身份验证并将令牌传递到下一个端点
【发布时间】:2020-06-29 19:18:03
【问题描述】:

我是基本身份验证和令牌的新手。

我一直在玩邮递员,以便使用基本身份验证获取令牌,然后将令牌作为不记名令牌传递以访问另一个端点。我想知道如何使用 node 和 express 将其编码为 api 调用。

我知道对于基本身份验证,我需要将客户端 ID 和密码编码为 base64

curl --request POST \
--url http://localhost:8080/token/ \
--header 'authorization: Basic ***' \
--header 'content-type: application/x-www-form-urlencoded' \
--data 
         grant_type=credentials

我从上面的调用中得到的令牌我想传递给下面的调用

curl --request POST \
--url http://localhost:8080/login \
--header 'authorization: Bearer ***' \
--header 'content-type: application/x-www-form-urlencoded' \
--data 
         user=1

这在节点应用程序中如何作为代码

【问题讨论】:

    标签: node.js express authentication token


    【解决方案1】:

    为此我会推荐 json web token aka jwt。

    现在我在 express、mongodb 中编写 REST API,并且我正在使用 jwt 进行身份验证。 由于我不使用任何前端框架或库,因此我使用 cookie 来存储 jwt 令牌。

    const jwt = require('jsonwebtoken');
    
    
    const generateToken = (res, id, auth_level) => {
    
      const token = jwt.sign({id, 
                              auth_level
                            }, process.env.JWT_KEY, {
        expiresIn: '7d'
      });
    
      return res.cookie('token', token, {
        expires: new Date(Date.now() + 1000 * 60 * 15),
        secure: false, 
        httpOnly: true,
      });
    };
    
    module.exports = generateToken
    

    在此示例中,我在成功登录尝试时调用此函数。然后在每次路由访问时,使用中间件我尝试解析用户是否拥有此令牌并尝试解析令牌。

    const jwt = require('jsonwebtoken');
    
    // Verify user token from cookie
    const verifyToken = async (req, res, next) => {
    
        // Get token from cookie named token
        const token = req.cookies.token || '';
    
        try {
    
            // Check if cookie exists, maybe expired maybe user didnt have one - no login
            if (!token) {
                return next();
            }
    
            // Decrypt users jwt token and get information
            const decrypt = await jwt.verify(token, process.env.JWT_KEY);
    
            // Pass that infomation to request user object
            req.user = {
                id: decrypt.id,
                auth_level: decrypt.auth_level,
                test: 'test'
            };
    
            // Continue with exectution of app
            return next();
    
        } catch (err) {
    
            return res.status(500).json(err.toString());
    
        }
    };
    
    module.exports = verifyToken;
    

    如果此令牌有效,我将自定义用户对象传递给 req 对象。

    在此之后,我使用自定义中间件保护路由。代码灵感来自this教程,会推荐它。

    【讨论】:

      猜你喜欢
      • 2021-04-13
      • 1970-01-01
      • 2020-04-10
      • 2015-02-24
      • 2021-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-16
      相关资源
      最近更新 更多