expresssession mysql_使用passport.js,mysql和express-session保持登錄狀態

魏泰
2023-12-01

2

You can use session (express-session) to achieve that. I currently using this combination express, express-session, express-mysql-session (for the storage), passport with facebook and twitter strategies. An a basic setup could be something like this.

您可以使用會話(快速會話)來實現這一目標。我目前正在使用這種組合快遞,快遞會話,快遞 - 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'));

More info at:

更多信息:

https://github.com/expressjs/session

https://github.com/chill117/express-mysql-session

 类似资料: