[英]How to implement session with express-session?
I'm considering using session in my node.js application. 我正在考虑在node.js应用程序中使用会话。
I understand the following: - session-cookie use cookie to save session data on the client side - express-session use cookie to store a sessionID and all the session data are stored on the server side 我了解以下内容:-会话cookie使用cookie来在客户端保存会话数据-快速会话使用cookie来存储sessionID,并且所有会话数据都存储在服务器端
I'm worried about security so I would choose express-session. 我担心安全性,因此我会选择快速会话。 But the Documentation say that by default express-session store data in memory and this not envisageable in production. 但是文档说默认情况下,快速会话将数据存储在内存中,这在生产中是不可想象的。
So my questions are: How do you implement session in your application? 所以我的问题是:如何在应用程序中实现会话? Do session stores are not influencing performance? 会话存储是否不影响性能? If not, which session store would you recommend me? 如果没有,您会推荐我哪个会话存储? (my application is using MySql as database) (我的应用程序使用MySql作为数据库)
Thank you very much for your help. 非常感谢您的帮助。 Regards. 问候。
The easiest way I found to manage session data is tokens. 我发现管理会话数据的最简单方法是令牌。
You can easily use 'passport' for expressjs and nodejs. 您可以轻松地对expressjs和nodejs使用“ passport”。
You can generate a token that is signed in your NodeJS backend with a private key and identifiable by the public key. 您可以生成一个令牌,该令牌在您的NodeJS后端中用私钥签名并且可以通过公钥识别。 These tokens can even be revoked. 这些令牌甚至可以被吊销。
They are passed into the 'authorization' header as a web standard. 它们作为网络标准传递到“授权”标头中。
Here is an example of validation I use for extracting and checking a generated token a user has provided. 这是验证的示例,我用于提取和检查用户提供的生成令牌。
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});
}
});
};
And here is my REST API call for a user attempting to login: (that generates a valid token) 这是我的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});
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.