Node express server session management middleware? - node.js

I want to do only cookie based authentication for my app. No pwd or email need to be given.
It is like the guest user feature in some webapps (like discord). You can use the app like
a logged in user as long as you have that cookie (or local storage). I find this very seamless and I don't want to put up signup barrier to the visitors.
I want a middleware, which does the following :
If request does not have a session id, it has to create a new session (by adding new document in sessions collection in mongodb, and setting the field session_id with random string)
If the request has cookie, it has to parse the cookie and set in request object. Even better, it gets the session object from db and set it in request object.
Is there anything right out of the box that does this? Or any other ways to easily achieve this?

express-session with a mongodb data store will do that pretty much right out of the box. There are multiple session store options for mongodb here. One of them is even maintained by the mongodb team.
In a nutshell, express-session will check for an incoming session cookie. If one exists, it will look up the session ID in the session store and find the session object for that ID. If there is no cookie or the DB has no session for that ID, it will make sure there's a cookie and create a new session for it. That session will be available as req.session for that request for all request handlers and middleware downstream of the session middleware.
You will need to age away old sessions from mongodb because if you're not attaching any login to them, then lots of the sessions will get permanently orphaned either when the user never comes back to your site or when the user's cookie ages away. And, the same user from multiple devices will cause multiple separate sessions to be created (which is a by-product of the auto-session-creation and login-free design).

Related

How to reinitialize express session within request logic?

Sorry, I don't know the best terminology to do what I am wanting to do.
I have several microservices that share a session secret. Once in a while, the session secret changes, and I will want to "refresh" the microservices with a new session secret.
In the case where, say, two of the microservices get the new secret but one of them doesn't, if the session cookie is signed with a new secret that the microservice does not have, then I can see the session cookie, but sessionID is not populated. This is how I determine if I need to refresh the session secret. So the microservice is able to grab the new secret and add it to the array of session secrets that was passed to express-session during initialization.
However, I was hoping that after this I could try to get the session again using the ID in the session cookie, and return the authenticated page to the user. The problem is, at this point express-session has already done its work, and there is no session present due to the fact that the ms saw a seemingly invalid signature. Currently my solution is to redirect back to the page after session secret is refreshed:
res.redirect(req.originalUrl)
This seems to be working, but is less than ideal. I was wondering if there is some way to tell express to go back to square 1, where it gets a session ID and verifies the signature, and then populates the session if it is present, without a redirect or anything, and once that is done continue to go through all the middleware as if this was a new request.
Any help would be appreciated

How do I know when a session has expired?

I'm learning to use the "client-sessions" package in Node.js, with Express. Everything seems to be working well. But I'm wondering, is there is a way to have it call a function if a session expires?
I'm setting things up so that the session only stores a unique ID. Then outside of the session I store all the user data and anything else I need. That way it keeps my cookies and session info very small. But I want to know when a session has expired so that I can clear any info that doesn't need to be kept after the session is gone.
But I have not been able to find any details on how to do this. Am I thinking about this in the wrong way? If I store everything in the session it will try to store it all in the cookie as well won't it?
thanks in advance.
Making my comments into an answer since it appears to have helped you solve your issue...
If you use a session manager like express-session that only stores a session ID in the browser cookie and keeps a session object server-side in the session store, then you can just store your data directly in the session object and when the session expires, the session manager will just automatically clean up the session (including your data in the session). Then, you don't have to worry about when it expires as things are just managed for you automatically.
express-session has the ability to look up a given session in the session store.get(sessionID, callback) where store is the session store object you're using. To use that, you need to have previously saved the sessionID for a given user that you want to look up.

Confused about nodejs (and the Passport middleware) sessions

Super simple question that I'm having trouble wrapping my head around.
When using sessions with nodejs, are the sessions stored in the users browser? Or are the sessions stored on the server?
For example, if I'm using the express-session or passport.session(), where are these session cookies stored?
As #robertklep mentioned, sessions (in the way you're using them) are stored on the client, but only contain a session ID. When your request hits the web server, it'll then look up the session ID to grab the account from some sort of database / cache, then use it for the remainder of the request lifecycle.
If you're interested on learning more about this, you might want to check out this screencast I made a while ago which covers exactly how cookies work, and why -- as well as how to store them securely: https://www.youtube.com/watch?v=yvviEA1pOXw
Furthermore, if you're looking to build a site that doesn't use 'typical' server-side sessions, and works with modern client-side front-end web frameworks like Angular.js / React.js / etc., you might want to investigate JSON Web Tokens (JWTs). These tokens allow you to create 'dumb' cookies that don't require a database lookup on the server, and can speed up your web apps / API services pretty dramatically: https://stormpath.com/blog/build-secure-user-interfaces-using-jwts/
Hope this helps!
The fine manual states:
Note Session data is not saved in the cookie itself, just the session ID. Session data is stored server-side.
express-session sends a cookie to the browser (which stores it), which contains a unique session id. The data itself is stored on the server (depending on which session store you use, this can be in memory, Redis, MongoDB, ...).
The session id in the cookie is merely used as a key to look up the actual data in the session store.

ExpressJS: how does req.session work?

I am writing an ExpressJS backend with User login support. From multiple examples I see the use of req.session object. It seems this object is used to store and retrieve information across server and client, so the server can set a "logged" flag and later check this flag to see if the user has logged in.
My question is, how exactly does this work? How does the server store information on the client and retrieve it from every request, is it through cookies? Is it possible for a client to manually manipulate the content of this object on the client side to foil security? If it is, what is a more secure way to check user login?
I found something from the ExpressJS Google group, so a session and cookie is a bit different in ExpressJS. Basically:
Res.cookie adds a cookie to the response; req.session is a server-side
key/value store. Session data lives in server memory by default,
although you can configure alternate stores.
You can store anything you want in a session. The only thing the
client sees is a cookie identifying the session.
(Credit goes to Laurie Harper)
So it seems ExpressJS is already doing what #Vahid mentioned, storing the values on the server and saves a key as a cookie on the client side. From my understanding, req.session uses its own cookie (which contains just a key), independent from req.cookie's custom cookie.
Actually session object in req.session is not passed by client. In your syntax u might have used app.use(session{options})
This is a middleware. Now each request that is passed from express server has to be passed through this middleware. This middleware fetches the cookie(just an encoded version of sessionId stored on server) and decodes it to get the sessionId. The session corresponding to that sessionId is fetched from server and attached to req object as req.session. It gives a feel that we are getting session from client side, but actually it is the work of middleware to attach session object to req object by getting the cookie from the client.
I don't know your exact implemention, so I don't comment specifically for your case. But generally you can verify what's being sent from browser to server on each request, you can install a firefox extension like "Live HTTP Header" or "Tamper Data" or even a wireshark (if not https) or firebug, firecookie etc.
Then check to see what's being sent via Cookie, I'm sure that ExpressJS thing after successfully authenticating user generates a session ID, stores it in a DB and stores same value in your browser cookie. On every request (even images) your browser sends cookie, server verifies session ID with db and detects your session.
I've seen some old unsecure codes which sets user's session with a value like loggedin=1, if it's your case, you have to know it's really easily bypassable. You have to generate, save and set session ID per client.

Where are store SessionID on the client

I have a web site in ASP 3.0. This web site initialize authentication by session on the server, and retreive the id of the user in the session. A multiple clients access to the web site with no problem.
Some of them lost there session. I think is due to a client configuration with the sessionID token or someting like that.
Could some body tell me where are stored the sessionID on the client machine.
Thanks.
I read this post and just need to know what will be the name of the cookie ? Is it the same cookie that we can read/write in code ?
I try to find a way to identify, the sessionID storing on the client machine and the connected session on the server. Did a way to do that ?
The server allocates a session and stores its ID in a cookie, known as the session cookie. The ASP Session cookie has this format:-
ASPSESSIONIDACSSDCCC=APHELKLDMNKNIOJONJACDHFN
Note that last 8 characters in the name of the cookie will vary from one instance of your application to the next. Hence to even discover the cookie you need to enumerate all the cookies looking for any that match the pattern ASPSESSIONIDxxxxxxxx.
I'm not sure what you could usefully do with this cookie once you have acquired it.
Session ID's can be stored in multiple ways on the client but it's the server configuration that specifies the exact way. If possible, cookies will be used. Otherwise, the session ID might be part of the URL or be part of the web page itself as a hidden form variable.
Also, session ID's are often created to time out after a while. If a user isn't contacting the server within e.g. 20 minutes, the session expires and a new session would be required.

Resources