Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 725
Xavier_Ex Avatar asked Dec 21 '22 10:12

Xavier_Ex


2 Answers

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.

like image 152
Xavier_Ex Avatar answered Dec 26 '22 00:12

Xavier_Ex


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.

like image 42
Ankush Sharma Avatar answered Dec 26 '22 02:12

Ankush Sharma