Node.js 基本身份验证和向下一个端点传递令牌
我不熟悉基本身份验证和令牌 我一直在玩弄postman,以便使用基本身份验证获取令牌,然后将令牌作为承载令牌传递给另一个端点。我想知道如何使用node和express将其编码为api调用 我知道,对于基本身份验证,我需要将客户机id和密码编码到base64中Node.js 基本身份验证和向下一个端点传递令牌,node.js,express,authentication,token,Node.js,Express,Authentication,Token,我不熟悉基本身份验证和令牌 我一直在玩弄postman,以便使用基本身份验证获取令牌,然后将令牌作为承载令牌传递给另一个端点。我想知道如何使用node和express将其编码为api调用 我知道,对于基本身份验证,我需要将客户机id和密码编码到base64中 curl --request POST \ --url http://localhost:8080/token/ \ --header 'authorization: Basic ***' \ --header 'content-type:
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
作为节点应用程序中的代码,我建议使用json web令牌aka jwt 现在,我在express、mongodb中编写RESTAPI,并使用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对象
在此之后,我用定制的中间件保护路由。代码的灵感来自教程,建议使用