Joenel de Asis
Joenel de Asis

Reputation: 363

Node.js cookies and session management

After surfing the web about cookies and session I am creating a simple login in nodejs using express with cookie/session using redis as my data storage.

What do you think is the best way to handle cookies/session after the user logs in? I also have these question in my mind:

  1. How do i prevent using userA cookie to inject to userB's browser?
  2. Do I need to check the value of the cookies before performing any process?
  3. Using cookieParser is it safe that the connect.sid is unique in every browser?
  4. app.use(session({secret: 'secretkey', key: 'quser'})); what is this secret all about?

I can't make up my mind on how i'm gonna use them in a proper way. Thanks guys.

Upvotes: 1

Views: 4517

Answers (2)

Alexei
Alexei

Reputation: 249

According to the session middleware (https://github.com/expressjs/session)

secret - session cookie is signed with this secret to prevent tampering.

Secret option will make sure your cookie is not modified.

There is a lot written about stealing cookies and preventing Cross Site Scripting. One of the possible ways to do it is make the cookie unavailable for javascript by providing the option httpOnly : true

cookie - session cookie settings. (default: { path: '/', httpOnly:
true, secure: false, maxAge: null })

Do I need to check the value of the cookies before performing any process?

Usually you keep in the cookie some information identifying your session and session data is kept on the server. You can do it yourself but there are some great libraries which could help. One of the most popular to handle authentication in express is passport.js (http://passportjs.org/)

While using passportjs you will implement two methods serializeUser and deserializeUser. They will be called on each request to get the user data based on the identity saved in the cookie. Here you can use for example mongo or redis

Upvotes: 2

Nathan
Nathan

Reputation: 409

Use a library.

It is such an easy thing to make a tiny mistake with disastrous consequences.

I've used Passport before and liked it a lot.

This was a similar question that had some very good replies: user authentication libraries for node.js?

Upvotes: 2

Related Questions