how to check session store used by node application - node.js

Currently, I have a node application where I need to check the specific session store I am using to manage store session variables. I never explicitly configured this (though someone else working on the same codebase could have) and haven't been able to find anything specific, and I need to know if the session store uses the touch method to know if I should set the resave proprty of sessions to true or false.

First of all, you need to locate the express-session usage in your code base.
Should be in your server.js or app.js file. Being used as
app.use(session({...properties}));
For example it may look like this:
app.use(session({
saveUninitialized: true,
resave: true,
secret: 'secret-123',
cookie: { secure: false, httpOnly: true, maxAge: 60000 },
store: new CouchbaseStore({
db: connectionObj,
prefix: 'test'
})
}));
the default store is the Memory of the server. So you can override the store with connect-mongo, connect-couchbase, connect-redis and what not.

Related

Understanding Express session in NodejS

I was trying to comprehend express-session from the docs and I am unable to get some points
Consider this code, which I found from a repo
app.use(session({
resave: true,
saveUninitialized: true,
secret: 'aaabbbccc',
store: new MongoStore({
url: MONGO_URI,
autoReconnect: true
})
}));
Now, I probably get what is happening here but still just to confirm
resave: true according to the doc will mean that it will force to save session back to the session even if it hasn't changed. Okay Cool? But why would someone force to save a session when it isn't changed and what difference will make it make?
saveUninitialized: true Here we are storing the session for non-logged in user as well?
And Finally if someone could explain this line of code as well (which I am unable to comprehend)
store: new MongoStore({
url: MONGO_URI,
autoReconnect: true
})
Moving on, In the above code, the author of the repo isn't storing the session in the cookie? and is just storing the cookie identifer?
And lastly, In the description they have mentioned/talked about cookie.httpOnly, cookie.expires and cookie.domain
Now, I understood their functionality but am unable comprehend their implemention, so if anyone could showcase implementation for any one of them?
These are my understandings. I might be wrong.
May be resave is used for certain storage driver to keep session alive!? I don't have anything in mind right now.
saveUninitialized is true means, a session will always be created. Experiment: Create a simple express server. Configure express-session and keep that value true. Don't create any session manually. Hit any endpoint of your server from browser. Open developer options and look for cookies. You will see a cookie has generated. Now, remove the cookie. Change the value to false and hit the endpoint again. No cookie will generate this time.
If you don't mention any store then all sessions will be stored in MemoryStore which is build only for development purpose. So in production you should always use some sort of persistent storage. There are a good numbers of storage options available.

express-session secure: true

app.use(session({
secret: "testing credentials",
store: sessionStore,
resave: true,
saveUninitialized: true,
cookie : {
httpOnly: true,
//secure: true,
maxAge : 60 * 60 * 1000
}
}));
I'm working on some security problems on my newly developed website. And after done some research online, if secure=true is set, then it will be more secure. However,
If set secure: true, then information inside session will lose every time when the user send another request. Is there a way to solve this problem? If doesn't include "secure: true" in the cookie: , then the session will last for that maxAge.
If a cookie is set with the secure flag, it will only be sent to the server by the browser over https, and not plain http. This should be the default for production environments.
However, when developing an app, you probably use plain http on your dev machine. If you set your session cookie as secure in this case (using plain http), the server will never receive it, and you will experience a new empty session on each request.
So in short, you should only set the cookie as secure if you are using https (that is, in later stages of your development pipeline, and definitely in production).
On another note, if you set maxAge, the cookie will be persisted, which is not the best practice for session cookies. Without maxAge, the cookie will be kept until the user closes the browser and not normally persisted to disk, which is the correct behaviour for session cookies.

My Node.js web app establishes new session every time I reopen the browser

Every time I close all the browser windows and then open the web app again, a new session is established, that means I have to authenticate again.
For your reference, I use express#4.14.0 as the web application framework, express-session#1.14.1 + connect-mongo#1.3.2 as middleware to store the sessions and passport#0.3.2 for authentication.
Below is the code for cookie and session configuration:
// CookieParser should be above session
app.use(cookieParser());
// Express MongoDB session storage
app.use(session({
resave: true,
saveUninitialized: true,
name: config.sessionName,
secret: config.sessionSecret,
store: new MongoStore({
mongooseConnection: db.connection,
collection: config.sessionCollection
})
}));
The "old" session stored in MongoDB still has two weeks to expire.
It seems like the Node.js application cannot recognize the "old" session from browser, therefore create a "new" one and tell the browser to use the "new" one.
It does not happen occasionally, but always, so I believe there is something wrong in my web application.
Thanks to #Bradley, finally I figured out what's wrong.
This is my solution
app.use(session({
cookie: {
maxAge: ms('14 days') // `ms` is a node module to convert string into milliseconds
},
resave: true,
saveUninitialized: true,
name: config.sessionName,
secret: config.sessionSecret,
store: new MongoStore({
mongooseConnection: db.connection,
collection: config.sessionCollection
})
}));
For more information, please refer to https://github.com/expressjs/session#expires
By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and will delete it on a condition like exiting a web browser application.
That's why I encountered this problem.

Session handling in mean stack

I am new to MEAN stack, presently the mean stack is inserting sessions to mongodb:
app.use(session({
saveUninitialized: true,
resave: true,
//cookie: { maxAge: 600 },
secret: config.sessionSecret,
store: newmongoStore({
db: db.connection.db,
collection: config.sessionCollection
})
}));
But I want to save some custom variables in that session & access them across requests, I did not get how to save it in session. Let's say I want to save mydata in session, I saw some examples & tried like:
req.session.mydata = 'projectdata';
req.session.cookie.mydata = 'projectdata';
Both are not working. Also I want to update maxAge variable on every request to server side, how to do it? Kindly help me.
Better use Token based sessions, It will help you making you API universal ie, You can also use the same API for mobile applications.
Try implementing Token Based Authentication using psJwt.
You will find good articles for this on scotch.io and on Plural sight.

Node Express - difference between req.cookies and req.session.cookie

I am trying to find out what the difference is between req.cookies and req.session.cookie. I am using Passport for authentication in Node.js Express.
If I log these two lines in my code:
console.log('cookies',req.cookies);
console.log('session',req.session);
I get this output:
cookies { 'mysite.sid.uid.whatever': 's:Ltko5IdDgsAISG0smrKNYaeIVy8nbBzF.MkGmpnf6uUKITIAgN4ws3YXqxJrMaeeSCzlKdjQnqfI' }
session { cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true,
secure: false },
views: 8,
passport: {} }
I am using this configuration:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(busboyBodyParser());
//app.use(busboy());
app.use(cookieParser('cookie parser secret'));
app.use(session({
secret: process.env["SESSION_SECRET"],
saveUninitialized: true, // (default: true)
resave: true, // (default: true)
store: require('mongoose-session')(mongoose),
maxAge: 60000,
key: "mysite.sid.uid.whatever",
cookie: {secure: false}
}));
I don't really know the difference between using sessions or cookies, except that cookies are client-side only and sessions could be either client or server-side. I have read the documentation from Passport.js a few times, but I still don't really understand what is going on here. Can someone help me out with some explanation? As far as I can tell, it seems best to use server-side session using Redis. But I don't see how you can get away from using client-side data in the end. At some point, you have to rely on the client-side data stored right?
after I login with the express app, the passport object gets populated with a user field, with the MongoDB objectid.
passport: { user: 549290b8246f0e1408e48b13 } }
Typically you will be using cookies when serving browsers. The exception to this being authenticating via an HTTP header or POST parameter token, which are more typical for API requests for example.
It is true you can do client side or server side sessions using cookies, where the entire session data is stored in the cookie in the former (and does not use any storage server-side) or session data is stored server-side (with a session ID stored in a client-side cookie) in the latter.
req.cookies contains cookie values only, no matter if the cookies are session related or not. req.session.cookie contains the Set-Cookie parameters used in the client-side session ID cookie.

Resources