Why is there a cookie in the req.session in node express? - node.js

It's more for my understanding. Why is there a cookie object in the req.session in express?
I use req.session to store the login status and username.
The cookie object in req.session is the same as the cookie properties in the client cookie, placed by express.parseCookie but without sessionID.
Can anyone explain why this is in there?
It cant be for the purpose to identify cookie and session because thats already made by the cookie value and the session ID (req.session.ID), or am I'm wrong?
- req.session -->
{ cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true },
loggedIn: true,
username: 'luidpold' }

For convenience. It’s the cookie associated with the session, and you can query/modify it.
The session handler in Express comes from Connect. The documentation for Connect says:
Session#cookie
Each session has a unique cookie object accompany it. This allows you
to alter the session cookie per visitor. For example we can set
req.session.cookie.expires to false to enable the cookie to remain for
only the duration of the user-agent.
Session#maxAge
Alternatively req.session.cookie.maxAge will return the time remaining
in milliseconds, which we may also re-assign a new value to adjust the
.expires property appropriately.

Related

How to expires session when browser is close in passport.js

I want to expire session when the browser is closed.
I'm using res.cookie('testlocale', 'en', { maxAge: 900000, httpOnly: true });
Also which event should i use in front end(onbeforeunload or onunlod)
I'm not able to understand how to do this. I'm using handlebars in front-end
If you use express-session.
You can set expires: false.
req.session.cookie
Each session has a unique cookie object accompany it. This allows you to alter the session cookie per visitor. For example we can set req.session.cookie.expires to false to enable the cookie to remain for only the duration of the user-agent.
From docs
If you want to manually delete cookies on frontend, I think both are good fit. But I'm not sure it's good idea.

Secure cookies option in Express - how to access

In a node app, I want to use cookies to read data. If I want to make a cookie using the options:
res.cookie('user', '123', { signed: true, httpOnly: true, secure: true }
and later read the cookie in a node endpoint/controller:
router.get('/test', testHandler)
function testHandler(req, res){
// how to read the secure cookie here?
}
how can I access this secure cookie on my local machine? Would I have to set up an https server locally to be able to read it?
You can just do req.session
Remember if you set the secure attribute to true, the connection has to be made over HTTPS, otherwise it won't work.

Node.Js: Signed cookie can't be found

Using a MEAN environment (with express 4), I create a cookie like this.
//webserver.js
app.use(cookieParser(„somesecretkey“));
//somescript.js
res.cookie(‚testcookie‘, ‚testvalue', {signed: true, maxAge: 999999, httpOnly: true});
In another script, I try to check the existence of the cookie like this.
//someotherscript.js
if(req.cookies.testcookie){
console.log("COOKIE EXISTS“+req.cookies.testcookie);
}else{
console.log(„NO COOKIE“+req.cookies.testcookie); //always undefined
}
I checked the browser for the cookie and it definitely exists but the console keeps logging that there is no cookie (cookie undefined) when I press refresh or simply visit the page. As soon as I change the cookie to unsigned and remove the secret key, I can access it!? Why can’t the cookie be found once its signed?
The expressjs documentation for res.cookie tells us:
When using cookie-parser middleware, this method also supports signed
cookies. Simply include the signed option set to true. Then
res.cookie() will use the secret passed to cookieParser(secret) to
sign the value.
res.cookie('name', 'tobi', { signed: true });
Later you may access this value through the req.signedCookie object.
So:
did you specific a secret using cookieParser?
you should check for the cookie in req.signedCookie, not req.cookies

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.

Setting cookies in Express.js XHR response object from node_redis callback

I'm having trouble getting a cookie to be passed back with an Express.js response. The situation is that I'm making an XHR containing user credentials, checking if the user exists, if the user does exist and credentials are correct I store the users info in Redis via node_redis. In the callback that I hand Redis I create a cookie on the response object, then send the customer object to the browser.
Here is the Redis code (note: I'm not using Express sessions so I just added the Redis client into req.session via middleware):
req.session.hmset('user', customer, function(err, status) {
res.cookie('sid', 'sessionID', {
maxAge: 3600000,
path: '/',
httpOnly: false
});
res.send(customer);
});
The odd thing is that when I add a console.log(res._headers); right after creating the cookie, there is a 'set-cookie' header present, but it never makes it to the browser. Might I have bad request headers? Something else? I'm completely stumped here...

Resources