Express 4- How to set a additional custom cookie with Session? - node.js

From reading Express 4 Session Documention
It states:
the cookie-parser middleware no longer needs to be used for this
module to work. This module now directly reads and writes cookies on
req/res. Using cookie-parser may result in issues if the secret is not
the same between this module and cookie-parser.
If I want to set a additional custom cookie, such as loggedIn: true, how would I do that with Session? I don't see any apis to set cookies other than the default one it makes for it's session tracking. And as the docs state, I should not use cookie-parser with express-session.

Found out through express.js github:
The documentation does in no way say you cannot use the two together.
It just state that using cookie-parser is not actually required to use
this module now (it used to be required in older 1.x versions) and
that just keep in mind you have to use the same secret for this module
and cookie-parser if you use the cookie-parser module.

To store or access session data, simply use the request property req.session, which is (generally) serialized as JSON by the store, so nested objects are typically fine. express-session
As it says, you can directly write to req.session
req.session.loggedIn = true

Related

What is the additional information in connect.sid cookie string apart from the session id?

I am using Node JS with express-session.
One question answered here advises to use req.cookies['connect.sid'] to get the session ID. Another answer suggests I use req.sessionID
When I compare the two the req.cookies['connect.sid'] has a string like the following:
s:G1wOJoUAhhemRQqCs7dAGlMIk5ZGaJUg.z1/HrHTfndRqKpXza8qWuwHLS067xrWfVgqTDDGYoos
req.sessionID has a string like the following:
G1wOJoUAhhemRQqCs7dAGlMIk5ZGaJUg
If the second string is the session ID (G1wOJoUAhhemRQqCs7dAGlMIk5ZGaJUg), what is the other information in the connect.sid cookie?
Tried looking for the answer via google and other websites with no luck.
Thanks,
Darren
express-session stores all session information server-side. If you use an sql database, you'd have a table for your sessions, that would look like this :
sid | sess | expire
R02GJn2GoyaqRyten1BEGbHa0XCbj529 | {"cookie": "originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"},"mybool":true,"userid":16}
That's the answer to your question, and a short explanation of what the data means, sessionID is just a (primary) key to access the data that is only available server-side.
Now from your question it looks like you're planning on using express-session wrong.
To use express-session on your express server you would include it like so :
const session = require('express-session');
app.use(session({
name : 'mycookie',
secret : 'mysecret',
saveUninitialized : false,
resave : true
}));
and every request that goes into all subsequent routes after this will have a .session attribute. In any case, you should never need to access the session id yourself, the middleware itself authenticates every request against whatever store you used for express-session.
app.get('/givemeasession',function(req,res,next){
req.session.mybool = true;
req.session.somedata = 'mystring';
req.session.evenobjects = { data : 'somedata' };
res.send('Session set!');
});
app.get('/mysession',function(req,res,next){
res.send('My string is '+req.session.somedata+' and my object is '+JSON.stringify(req.session.evenobjects));
});
Bottomline : you shouldn't ever need to access the cookie yourself, or do anything with it, because any cookie auth is automatically handled by the middleware.
The accepted answer is correct by saying, don't handle cookies and sessions by yourself, but I don't think it answers the question:
The second part in connect.sid is the cookie signature.
In case of express-session this is generated by the package cookie-signature with the secret you set when you set up the session middleware.
As you can see in the source-code, the very first step is verifying if the cookie was signed by the secret. Afterwards the cookie is retrieved from the store.
(In case of the memory store, the retrieval also deletes the cookie if expired)
Source: https://github.com/expressjs/session/blob/1010fadc2f071ddf2add94235d72224cf65159c6/index.js#L542

How to read PassportJS session cookie with ngx-cookie?

I'm learning Angular with a MEAN stack project. Full code is here: Angular front-end, Node.js API.
On the back-end, I use Passport authentication with the default session-based behaviour, and I have local, Google and Facebook strategies set up. Passport will insert user data in the session cookie, to be parsed and used by the front-end to display user name, email address, profile pic, etc.
So now in the back-end, what I need to do is retrieve the cookie and deserialize it, then write methods to use said cookie to get user data, as well as a basic isLoggedIn(), that would just check if a valid cookie is present.
To do that, I've tried both ngx-cookie and ngx-cookie-service and have the same problem with both: I can create and read a cookie that I've created, but the 'session' and 'session.sig' cookies created by Passport remain invisible to the getAll method (and any get('session')).
All code handling that is inside authentication.service.ts. Currently all methods are meant for a token-based auth, so I need to change them. Specifically, this is the method I use to test cookie handling:
public getCookies() {
this.cookies.set('test', 'yay');
console.log('test: ', this.cookies.check('test'));
const allCookies = this.cookies.getAll();
console.log('allCookies: ', allCookies);
return allCookies;
}
The console output of that code shows only one cookie, 'test'. On the browser dev tools, I see there are two more cookies, 'session' and 'session.sig', that I want access to. But how?
Thanks!

Authentication & Sessions in express.js/sails.js

Have been working through the sails cast tutorials and am confused about the way that sessions work.
In the tutorial, the user is marked as authenticated in the session controller by:
req.session.authenticated = true;
req.session.User = user;
res.redirect('/');
Why is the session being saved in the request?! My understanding is that the 'req' object in express.js is the information the browser sends to the server.
Shouldn't the server save this information elsewhere (won't the request object be deleted when theres another request?)
Furthermore, somehow the application retrieves the authentication status from another object session when templating a page with ejs:
<% if (session.authenticated) { %>
why isn't this variable set directly?
Probably a silly question but I am confused at how the logic works and online articles/tutorials aren't helping me understand...
It is common practice for express middleware (remember, Sails is built on express) to attach properties to the req object so it may be accessed in later middleware, and eventually your controllers. What happens behind the scenes is your req object comes in with a cookie containing the session ID, and then the session middleware uses that to retrieve the actual session data from some datastore (by default, and in-memory store is used. Super fast and easy for development, but not recommended for deployment), and then attaches that to the req object.
Regarding the value of session.authenticated in your EJS, by default Sails includes req.session in res.locals (accessible in views), so that value will be whatever is stored in the session via your controller.
The browser sends over the session id which is stored on a cookie. The session object is referenced by that session id which is stored server side. The session is attached to the request (for convenience I suppose). You can read more here https://github.com/expressjs/session#compatible-session-stores
I wouldn't know what is setting session.authenticated without seeing more code.

Usage of cookie-parser with passport.js still needed?

Can not find any info (on passport.js site) about general passport.js instalation and declaration in node.js.
In the tutorials I always see express session middleware and cookie-parser stated as required for passport, yet session docs (https://github.com/expressjs/session) notes:
'Since version 1.5.0, the cookie-parser middleware no longer needs to be used for this module to work. This module now directly reads and writes cookies on req/res. Using cookie-parser may result in issues if the secret is not the same between this module and cookie-parser.'
So do I need to use session & cookie-parser for passport for some reasons, or I can use only session, am I need to tweak something then?
No, passport itself does not require cookie-parser middleware. If you want session-persistent authentication then you'll need the express-session middleware, which used to require cookie-parser, but modern versions of express no longer have this requirement (the current version of express-session reads and writes cookies directly).

Is a session always created when using express js?

Assuming one sets the cookieParser in a Node application using Express JS, does it mean that a session will always be created if none is not available in the incoming request?
self.app.use(express.bodyParser());
self.app.use(express.cookieParser());
self.app.use(express.session({...]);
In other words, does req.session will ever be null or undefined?
Yes, the session middleware will put a session object on each request given your code above. Not the cookie parser has one well-defined job: parse the cookie header from HTTP header key/value to JS object. End of story. It's the session middleware that handles creation and population of the session object.

Resources