A session identifies a particular client. The general idea is that the session object and any data you put into the session object persists on the server. When a user makes a request to your server, they present the session cookie which your session infrastructure looks up and fetches the appropriate session object. Your request handlers can then use that session object and the data you put into it for whatever you want.
The data in a session object is stored locally on your server so it is secure and cannot be messed with by the client.
How do I use them in a middleware to verify the user?
For authentication, one would typically create some state in the session object that represents whether the user has been properly authenticated or not. If not, you ask them for credentials. If so, you allow the request to proceed.
Here's some pseudo code for a middleware.
app.get("/login", (req, res) => {
// handle login page
res.sendFile("login.html");
});
app.post("/login", (req, res) => {
// check auth credentials from the login form
if (credentials good) {
req.session.authenticated = true;
res.redirect("/someOtherPage.html");
} else {
req.session.authenticated = false;
res.redirect("/login.html");
}
});
// middleware to allow access of already authenticated
app.use((req, res, next) => {
// check if session already authenticated
if (req.session.authenticated) {
next();
} else {
res.redirect("/login.html");
}
});
// route that relies on previous middleware to prove authentication
app.get("/somethingElse", (req, res) => {
// do something for this authenticated route
});
What the difference between session id and connect.sid?
A cookie has a name and a value. By default, the cookie name for express session is connect.sid
. The value for the cookie is an encrypted key that express-session uses as an index into the session store.
The session id is an internally unique id for each session object. It's used in the internal implementation of the session store. You don't really need to worry about what either of these are. They are used internally for various housekeeping purposes.
So connect.sid
contains the cookie value that is sent to the client and that the client presents back to the server. It's purposely obscured with encryption and made difficult to forge or guess so that clients can't guess session values. The session id is used on the server only and does need those types of protections.
So connect.sid contains the cookie value that is sent to the client and that the client presents back to the server.
so how can we know or verify the cookie sent back to the server is the correct one that servers sent to the client? – Eris