基本上,方法是。
- 创建一个函数以根据需要生成自定义令牌。
const sign = (data, secret) => {
//your logic goes here
}
- 创建一个验证令牌的函数。
const verify = (token, secret) => {
// returns error or decoded data
}
- 登录成功后想创建令牌时调用它
const login = (req, res) => {
// login code goes here say its success
const token = sign({id: _id}, process.env.SECRET_KEY)
res.json({token: token})
}
- 验证在受保护路由中收到的令牌。为其创建一个中间件函数。
function verifyToken(req, res, next) {
//token from the request header
const authHeader = req.headers['authorization'] // -> or key of your choice
const token = authHeader && authHeader.split(' ')[1]
if (token == null) return res.sendStatus(401) // if there isn't any token
try{
const data = verify(token, process.env.SECRET_KEY) => {
if (err) return res.status(403)
req.user_id = data.id // this one will let you read data in the calling service function
next() // pass the execution off to whatever request the client intended
}
} catch (err) {
res.send(err)
}
}
- 从令牌中读取数据
const getUserInfo = (req, res) => {
const id = req['user_id'];
// now you can get the user data using this id that we used while signing the token.
}
现在我知道令牌是由第 3 方提供的,只能由他们验证。
所以在这种情况下,
function verifyToken(req, res, next) {
//token from the request header
const authHeader = req.headers['authorization'] // -> or key of your choice
const token = authHeader && authHeader.split(' ')[1]
if (token == null) return res.sendStatus(401) // if there isn't any token
try{
// make the verify call to the 3rd party api by sending the token
// received in the request
const data = ApiCall();
/* set that data into the header, if you may want to use it later or
* do whatever you want to do.
*/
req.resp_data = data;
next(); // sent control to next function.
} catch (err) {
res.send(err)
}
}
希望这会有所帮助。