Using cookieParser () and cookieSession () together?

cookieParser() allows us to sign cookies with a secret offer, which is great for preventing unauthorized access. I understand that a cookie is signed with a special value to prevent falsification.

I just discovered cookieSession (), which I consider to be a great alternative to cookies stored on the server (I only store { loggedIn = true, userId=763487246824632} , it never grows).

But ... I found that setting "secret" for cookieParser () breaks things, and cookieSession () stops working if the secret sentence matches. The reason is that if a cookie is signed using the same secret, then cookieParser () actually takes it and analyzes it. It is strange that after cookieParser () has completed its work with the same secret signal, the session will be set to:

 { cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true } } 

Instead

 { testing: 'OOO' } 

(Each reboot adds an "o") So ...

  • Was my analysis clear?
  • Do you know why the session is set up for this strange { cookie if the secret offers match?

Merc.

+6
source share
1 answer

Your analysis is correct, I can reproduce it.

The problem is caused by this line in the cookieSession (in some context: options.secret is the key passed to cookieSession , req.secret is the key passed to cookieParser ): if you pass both middleware with a secret key, cookieSession assumes that he will find the raw cookie in req.cookies .

But since cookieParser also took the signed cookie (and it was run before cookieSession ), it analyzed the cookie itself (and since the signing keys were the same, it succeeded), saved it in req.signedCookies and deleted it from req.cookies . Regarding cookieSession , cookie is simply not set.

The object you see is the contents of the default session (which is a cookie property in the cookieSession configuration):

 app.use(express.cookieSession({ cookie : { // <-- this object ... } }); 

As for the solution: either use a different key for each middleware, or just pass one of them your secret key, but not both (on the understanding that if you pass it to cookieParser , all your cookies will be signed).

FWIW: I'm not quite sure that this is a real mistake. This is a consequence of using the same signing mechanism for both cookieParser and cookieSession , without distinguishing between cookies signed by one or the other. Although this can be fixed, always checking if the cookie is in req.signedCookies .

+10
source

Source: https://habr.com/ru/post/944680/


All Articles