Node js creating different session id for each request - node.js

Using express-session and storing session in files. However every request it is creating new session id and new file is getting created.
Here is the code which i am using to create the session.
app.use(session({ secret: 'keyboard cat',
resave: false,store: new FSStore(options),
saveUninitialized: false ,
cookie: { maxAge: 1000,secure: false,httpOnly: true }
}))
However i want it should create a single session id for each user or until session expires.

My issue was with MaxAge which I set it 1000 milliseconds i.e 1 sec. Therefore it was creating a new session id everytime. I have set it to 1 hour, it works fine.
Here is the complete code
var express = require('express');
var app = express();
var session = require('express-session');
var FileStore = require('session-file-store')(session);
app.use(session({ secret: 'keyboard cat',
resave: false,
store: new FileStore,
saveUninitialized: false ,
cookie: { maxAge: 3600000,secure: false, httpOnly: true }
})
);
app.get('/', function (req, res) {
if (req.session.views) {
req.session.views++;
res.setHeader('Content-Type', 'text/html');
res.write('<p>views: ' + req.session.views + '</p>');
res.end();
} else {
req.session.views = 1;
res.end('Welcome to the file session demo. Refresh page!');
}
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});

Related

Nodejs/Express/Cookies: how do you set signed cookies with a secret

In my directory i have app.js And Index.htmml ; I am trying to set cookies from App.js; I have tried:-
var express = require('express'),
app = express(),
http = require('http'),
cookieparser = require ('cookie-parser'),
httpServer = http.Server(app);
app.use(express.static(__dirname + '/data'));
app.get('/', function(req, res) {
let options = {
maxAge: 60000, // would expire after 1 minutes
httpOnly: true,
signed: true ,
secret: 'secret'
}
// Set cookie
app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }));
res.cookie('cookieName', 'Success', options)
res.sendFile(__dirname + '/index.html');
});
app.listen(8080);
When i run app.js from Cmd It dissappoints me with this error
Thanks in advance for help
Error: cookieParser("secret") required for signed cookies
You need to specify a secret key which will be used while signing the cookie.
You can do this by adding the following line to your code.
app.use(cookieparser("secret"));
According to the snippet, you are using the express-session module like so:
app.use(require('express-session')({ secret: 'keyboard cat', ... }));
That is already saying that you want cookies to be signed. Therefore, in your cookie options you can remove the option signed: true since it will be redundant.
And on a last note, you need to improve that code.

Cookie value not changing express nodejs

I am using Express Framework and socket.io. I am working on authentication part and I am unable to change the value of cookie. Please see the code.
var session = require('express-session');
app.use(cookieParser());
app.use(session({
secret: "kvkjsdsbj12334",
resave:false,
saveUninitialized: false,
cookie:{
authStatus: "NotLoggedIn",
secure: false
},
rolling: true
}));
app.use(function (req, res, next){
console.log(req.session.cookie.authStatus); // Logs NotLoggedIn after /login.
});
app.post('/login',(req,res)=>{
var body = _.pick(req.body,['email','password']);
var email = body.email;
var password = body.password;
Users.findByCredentials(body.email,body.password).then((user)=>{
req.session.user = user;
req.session.cookie.authStatus = "loggedIn";
req.session.save();
//Redirected from here
});
});

Redis not working on express-session

The code below is quite a normally snippet, but it's not working, session from request is undefined. Anyone who can give me a hint will be appreciated.
var express = require('express');
var session = require('express-session');
var redisStore = require('connect-redis')(session);
var app = express();
app.listen(3000);
app.use(session({
store: new redisStore({
host:'localhost',
port:'8543'
}),
resave: false,
saveUninitialized: true,
secret: 'somesecrettoken'
}));
app.get('/', function (req, res) {
if(req.session.isVisit) {
req.session.isVisit++;
res.send('<p>times to be here:' + req.session.isVisit + '</p>');
} else {
req.session.isVisit = 1;
res.send('1st time to be here');
}
});
A Redis client is required
var redis = require("redis"); // You can use any module to create redis client
app.use(session({
store: new redisStore({
client : redis.createClient(<your setting>)
host:'localhost',
port:'8543'
}),
resave: false,
saveUninitialized: true,
secret: 'somesecrettoken'
}));
Please refer this link:
https://www.npmjs.com/package/connect-redis
Pass the express-session store into connect-redis to create a RedisStore constructor.
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
app.use(session({
store: new RedisStore(options),
secret: 'keyboard cat'
}));

Node-Client-sessions vs express-session

I have this Node API that frontends a backend OAuth server. At the end of the SAML OAuth dance, I set the Bearer Token in a browser cookie.
// need cookieParser middleware before we can do anything with cookies
app.use(express.cookieParser());
// set a cookie
app.use(function (req, res, next) {
// check if client sent cookie
var cookie = req.cookies.cookieName;
if (cookie === undefined)
{
// no: set a new cookie
var randomNumber=Math.random().toString();
randomNumber=randomNumber.substring(2,randomNumber.length);
res.cookie('cookieName',randomNumber, { maxAge: 900000, httpOnly: true });
console.log('cookie created successfully');
}
else
{
// yes, cookie was already present
console.log('cookie exists', cookie);
}
next();
});
app.use(express.static(__dirname + '/public'));
Now I was introduced to a fancy NPM which does pretty much the same thing https://github.com/mozilla/node-client-sessions
While I was almost inclined on using this NPM, I bumped into express-session. https://github.com/expressjs/session - this is for server side sessions. But this also sets a cookie
var express = require('express');
var session = require("express-session");
var app = express();
app.use(session({
resave: true,
saveUninitialized: true,
secret: 'ABC123',
cookie: {
maxAge: 60000
}
}));
app.get("/test", function(req, res) {
req.session.user_agent = req.headers['user-agent'];
res.send("session set");
});
If my need to set only a bearer token in the browser cookie for subsequent API calls, which option should be my choice?
express-session is my go to.
If you look at what it took to accomplish the same thing with the two different methods, I think the answer is clear.
If all you want to do is set a client cookie that will enable the server to correctly authenticate future requests, express-session is awesome.
Here is an example set from another question I answered that uses MongoDB as a backend to store your sessions:
'use strict';
var express = require('express'),
session = require('express-session'),
cookieParser = require('cookie-parser'),
mongoStore = require('connect-mongo')(session),
mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/someDB');
var app = express();
var secret = 'shhh';
app.use(session({
resave: true,
saveUninitialized: true,
secret: secret,
store: new mongoStore({
mongooseConnection: mongoose.connection,
collection: 'sessions' // default
})
}));
// ROUTES, ETC.
var port = 3000;
app.listen(port, function() {
console.log('listening on port ' + port + '.')
});

how to store session data in file in expressjs?

When user login, i am storing data in session like this :
req.session.user = userData;
And it is working fine but when i restart in nodejs, the session is null. Then user need to login again.
I want to create a file based storage for session.But after a lot of search, i got the way to store data in database but i dont want to store session data in database. I want to store data in file.
Is there a nodejs module to store the session data in file?
You can use session-file-store. can refer below working example.
var express = require('express');
var app = express();
var session = require('express-session');
var FileStore = require('session-file-store')(session);
app.use(session({ secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
store: new FileStore,
cookie: { maxAge: 3600000,secure: false, httpOnly: true }
})
);
app.get('/', function (req, res) {
if (req.session.views) {
req.session.views++;
res.setHeader('Content-Type', 'text/html');
res.write('<p>views: ' + req.session.views + '</p>');
res.end();
} else {
req.session.views = 1;
res.end('Welcome to the file session demo. Refresh page!');
}
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
You can try connect-fs2.
var FSStore = require('connect-fs2')(express);
var options = { dir='./mySessionFolder' }; // specify your directory to store your session files
app.configure(function() {
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
store: new FSStore(options), // use it as your store
secret: 'your secret',
cookie: { maxAge: 7 * 24 * 60 * 60 * 1000 } // 1 week
}));
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
Butt isn't it something like whenever we logedin session data is store in file and we at the moment we logout session data which are store in file they may get delete...
its not a good idea to write session data in file , because you need to stores as key , value pair and have to parse it. if the user logout you need to delete particular session from file (otherwise the file may goes out of memory)
you say , you have stored session data in db , you need to add additional status information as key value pair in db. that status should only become false when the user terminates the seesion or session timeouts , otherwise it remains true even if server restart.with reference with this status you can hold the users.

Resources