Setting up sessions in an express application in several dynos heroku applications

I implemented some user authentication on one Heroku dinar using express (node.js) + mongodb and everything works fine. However, when I increase the number of speakers (more than 1), I cannot log in, I am constantly redirected to my login page, that is, my session was not established. Here is my code:

checkCookies = function (req, res, next) {

if(req.session.user){ res.locals.user = req.session.user; next(); } else{ res.redirect('/login'); } }; app.use(express.cookieParser()); app.use(express.session({ secret: '0GBlJZ9EKBt2Zbi2flRPvztczCewBxXK', cookie: {httpOnly: true, maxAge:14*24*60*60*1000} })); 

What is the best solution to handle shared session in express / node.js using mongodb?

+4
source share
3 answers

connect-mongo should meet your needs: https://github.com/kcbanner/connect-mongo

+4
source

Use the connect-mongo module with expression.

 var http = require('http'), express = require('express'), session = require('connect-mongo')(express) 

And then in your working session, settings for external storage. The code below will use a session from mongo, cookie and extra headers to allow cross-domain and jsonp.

 app.configure(function() { app.use(express.cookieParser()); app.use(express.session({ store: new session({ db: 'sessions' }), secret: 'yoursecret', cookie: { path: '/', maxAge: 1000 * 60 * 60 * 24 // 1 day } })); app.use(function(req, res, next) { res.header('Access-Control-Allow-Credentials', true); res.header('Access-Control-Allow-Origin', req.headers.origin); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept'); next(); }); app.set('jsonp callback', true); }); 
+5
source

The above answers are misleading as they imply that you cannot share cookie-based sessions through multiple speakers on Heroku.

I can use cookie sessions on multiple speakers if I use cookie-session rather than express session . What is missing from the first message in this thread is a secret value that is NOT passed to the cookie parser. This means that the node will assign an arbitrary hash to the parser every time the process restarts or when a new speaker rotates.

Doing the following work for me:

 app.use(express.cookieParser('0GBlJZ9EKBt2Zbi2flRPvztczCewBxXK')); app.use(express.session({ secret: '0GBlJZ9EKBt2Zbi2flRPvztczCewBxXK', cookie: {httpOnly: true, maxAge:14*24*60*60*1000} })); 
+4
source

Source: https://habr.com/ru/post/1488183/


All Articles