我有一个使用Passport.js通过Facebook验证用户的应用程序,并且可以成功完成。但是,每当我的node.js服务器重置时,用户都会被注销。
似乎快速会话是持久登录状态的方式,但我读过的每个答案似乎都说你必须使用mongodb或redis来实现这一点。我们正在使用Mysql。
有没有办法使用mysql的express-sessions来持久登录状态?
答案 0 :(得分:2)
您可以使用会话(快速会话)来实现这一目标。 我目前正在使用这种组合 express,express-session,express-mysql-session(用于存储),带有facebook和twitter策略的护照。基本设置可能是这样的。
var express = require('express');
var session = require('express-session');
var MySQLStore = require('express-mysql-session')(session);
var app = express();
var options = {
host: '',// Host name for database connection.
port: '',// Port number for database connection.
user: '',// Database user.
password: '',// Password for the above database user.
database: ''// Database name
};
var connection = mysql.createConnection(options);
var sessionStore = new MySQLStore({
checkExpirationInterval: 900000,// How frequently expired sessions will be cleared; milliseconds.
expiration: 86400000,// The maximum age of a valid session; milliseconds.
createDatabaseTable: true,// Whether or not to create the sessions database table, if one does not already exist.
schema: {
tableName: 'sessions',
columnNames: {
session_id: 'session_id',
expires: 'expires',
data: 'data'
}
}
}, connection);
app.use(session({
key: 'MyKey',
secret: 'MySecret',
cookie: {domain: '.mydomain.com', httpOnly: true, secure: false},
domain: '.mydomain.com',
store: sessionStore,
resave: true,
saveUninitialized: true
}));
/**
* Session handle for passport
*/
app.use(passport.initialize());
app.use(passport.session());
/**
* Check if user is authenticated in a route
*/
function authUser (req, res, next) {
if (!req.isAuthenticated()) {
res.redirect('/login')
} else {
next();
}
}
router.get('/hello', authUser, function(req, res){
//Code
});
/**
* Start the server on port defined by configuration
*/
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'));
更多信息: