Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate custom session id with express-session?

I am using Redis as session store and I would also like to create custom session id with express-session. So far I achieved was creating session with constant string like this:

redis configuration

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var compression = require('compression');
var session = require('express-session');
var redis = require('redis');
var RedisStore = require('connect-redis')(session);

var routes = require('./routes/index');
var api = require('./routes/api');

var app = express();
var client = redis.createClient();

// compress all requests
app.use(compression())

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
  secret: 'SECRET',
  resave: false,
  saveUninitialized: false,
  store: new RedisStore({ host: 'localhost', port: 6379, client: client}),
  cookie: {
    maxAge: 60000
  },
  genid: function(req) {
    return "myApiKey";
  }
}));
app.use('/', routes);
app.use('/request_api', api);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

which creates keys in redis like below:

127.0.0.1:6379> keys *
1) "sess:myApiKey"

However, I could not generate unique id with uuid as mentioned in doc here session-store github. I have tried inserting session value in my index routes file (routes/index.js) like this

/* GET home page. */
router.get('/', function(req, res, next) {
  req.session.user = "12345";
  res.render('index', { title: 'MyApp' });
});

But could not read value inside genid function due to value undefined. So, my question is:

Can I generate session id with uuid of any model like user->uuid? If yes, how can I do it?

Thanks, any help will be appreciated.

like image 621
surenyonjan Avatar asked Jul 31 '15 08:07

surenyonjan


People also ask

What is saveUninitialized in Express session?

saveUninitialized : When an empty session object is created and no properties are set, it is the uninitialized state. So, setting saveUninitialized to false will not save the session if it is not modified. The default value of both resave and saveUninitialized is true, but using the default is deprecated.

Does Express session use JWT?

JWT and Express-Session both accomplish the same thing. The difference is a browser does not allows a http-only cookie to be accessible through javascript. At then end they are both used for the same end. The jwt should be related to a session of a user, therefore the users permissions are the ones that matter.

What is session id in Nodejs?

The session is given an ID that both the client and server can reference. This enables the application to split the session data between that which is stored on the client-side and that which is stored on the server. For example, the cookie may tell the application the session ID and that the user is authenticated.


1 Answers

You can do like this.

   var crypto = require('crypto');
   var uuid = require('node-uuid');

You need to require node-uuid and then in genid function

genid:function(req){
     return uuid.v1();
},

or to avoid id collision

 genid:function(req){
     return crypto.createHash('sha256').update(uuid.v1()).update(crypto.randomBytes(256)).digest("hex");
 },

You can access session id anywhere in the application by req.sessionID.

like image 142
Rohit Choudhary Avatar answered Sep 23 '22 02:09

Rohit Choudhary