我发现管理会话数据的最简单方法是令牌。
您可以轻松地将“护照”用于 expressjs 和 nodejs。
您可以生成一个令牌,该令牌使用私钥在您的 NodeJS 后端进行签名,并且可以通过公钥进行识别。这些令牌甚至可以被撤销。
它们作为 Web 标准传递到“授权”标头中。
这是我用于提取和检查用户提供的生成令牌的验证示例。
module.exports.ensureAuthorized = function ensureAuthorized(req, res) {
return new Promise((resolve) => {
let bearerToken;
let bearerHeader = req.headers["authorization"];
if (typeof bearerHeader !== 'undefined') {
let bearer = bearerHeader.split(" ");
bearerToken = bearer[1];
req.token = bearerToken;
this.userPayload(req.token).then((result) => {
if (!result) {
return res.status(403).json({message:"Failed to verify token supplied in authorization header", data: null});
}else{
resolve(result);
}
});
} else {
return res.status(403).json({message:"Failed to supply token in authorization header.", data: null});
}
});
};
这是我对尝试登录的用户的 REST API 调用:(生成有效令牌)
let jwt = require('jsonwebtoken');
let config = require('../../misc/config');
global.atob = require("atob");
let mongoose = require('mongoose');
exports.getLogin = function(req, res) {
const btoaAuth = (req.headers.authorization || '').split(' ')[1] || '';
const [username, password, rememberMe] = atob(btoaAuth).toString().split(':');
if(username && password) {
usersModel.findOneAndUpdate({username: username},{lastLogin: new Date(),})
.exec(function (err, userResult) {
if(err) return res.status(500).json({message: "Server failed search users", data: err});
if(!userResult) return res.status(500).json({message: "Username invalid", data: err});
userResult.verifyPassword(password, function(err, isMatch) {
if (err) { return res.status(500).json({message: "Server failed to process user login", data: err});}
// Password did not match
if (!isMatch) { return res.status(403).json({message: "Password incorrect", data: err}); }
// Success
let token = jwt.sign({_id: userResult._id,username: userResult.username, exp: rememberMe === 'true'? Math.floor(Date.now() / 1000) + (60 * 60 * 24 * 365 * 100) : Math.floor(Date.now() / 1000) + (60 * 60) }, config.jwtSecret);
let obj = {};
obj['profile'] = userResult;
obj['profile']['password'] = undefined;
obj['token'] = token;
return res.status(200).json({message: "Successful login", data: obj});
});
});
}else{
return res.status(400).json({message: "Username and password are required", data: req.body});
}
};