Understanding how sessions and local authentication work in Express is something that is not as clearly documented on the Internet as you’d might expect.
This article aims to change that by going in-depth into how these concepts are implemented in Express based on my own understanding of the two.
I’ll be using the following npm
packages along with Express:
mongoose
– for MongoDb object modelingexpress-session
– for user sessionspassport
– for user authenticationpassport-local
– for a local authentication strategypassport-local-mongoose
– for easy authentication logic
If you’ll recall, Express works with a request-response cycle in which callback functions are tied to specific routes and have access to request
and response
objects, like so:
app.get('/', (request, response) => { // index logic });
Now let’s go over the building blocks for sessions and authentication, one by one.
express-session
express-session is an Express middleware used for persisting sessions across stateless HTTP requests. It expands on some key objects provided by both Express and Node.js.
Overview
Sessions are used for storing data about a user and presenting dynamic data based on a user’s identity. They rely upon saving session data to a cookie that is sent to the user’s browser and then received back in future user requests.
This module expands the Express request
object with the session
property (among other things), which itself is an object that can be used by other middleware.
By default it uses a MemoryStore
, an in-memory key-value database not intended for production use, to store the session
data. But you can and should plug in another memory store middleware when deploying a serious product.
It creates a session for every user by generating a special ID that serves as a unique key for the session
data. This ID is stored and sent in a cookie, while the session
data is saved in a memory store or cache.
This way cookies are very lightweight while more costly lookups to the database are reduced since the session
object containing all the session data is stored in-memory.
You can view the value of this ID in action by logging request.sessionID
when inside an Express route callback.
Conceptual Workflow
The way you would usually provide information for a session is through an HTML form element in a web page. You would “log in” a user through a POST request to your web server containing username and password values.
Your login page form would look like this:
<form action="/login" method="POST">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit">
</form>
And the route on your app.js
would be something close to this:
app.post('/login', (request, response) => { // login logic goes here });
At this point you would need to store the login information somewhere in order to create a user session. Passport does exactly this, but we’ll get into that later.
Let’s understand what goes on once you use express-session in your project.
When a new session is created for a user:
- A special ID is generated and the
session
object is appended torequest
. - The special ID is encrypted with a secret provided by the developer and is written to the HTTP response header as a cookie that eventually reaches the user’s browser.
The express-session module expands the standard response.end()
method of the Node HTTP module, and ensures that the special ID and the session
are saved to the memory store near the end of the request-response lifecycle.
When a user is browsing our web site/web app under a session:
- The browser sends the cookie containing the ID for the session as part of the HTTP request.
- express-session parses and decrypts the cookie.
- express-session reads the ID.
- express-session retrieves the
session
data from the store. - express-session appends the
session
object as a property in therequest
object, restoring the stored session for the new request.
Plugging It into Express
In app.js
add the following require statement:
const session = require('express-session');
Also add the following configuration as well:
// express-session must be used before passport app.use(session({ secret: 'Insert randomized text here', resave: false, saveUninitialized: false }));
Now a session (ID and object) will be created for every unique user across multiple HTTP requests.
However, right now the session
object is not storing any important information. That is where passport comes in to take advantage of this functionality for implementing user authentication.
passport
Passport is a module that provides and automates user authentication for Express. It is mostly used to support authentication sessions over HTTP.
Configuration
In app.js
add the following require statement:
const passport = require('passport');
To configure passport correctly, you need to provide three things:
- An Authentication Strategy
- Application Middleware
- Sessions
Authentication strategies are a way for passport to delegate authentication to other modular packages. For example, there are Node packages that provide passport authentication strategies for Facebook and Twitter, etc.
For our local use case, the strategy is provided by the passport-local package. Passport provides the use()
function for plugging in the strategy (we’ll be doing that differently later), and it generally looks like this when using mongoose:
const passport = require('passport'), LocalStrategy = require('passport-local').Strategy; passport.use(new LocalStrategy( function(username, password, done) { User.findOne({ username: username }, function (err, user) { if (err) { return done(err); } if (!user) { return done(null, false, { message: 'Incorrect username.' }); } if (!user.validPassword(password)) { return done(null, false, { message: 'Incorrect password.' }); } return done(null, user); }); } ));
You’ll notice that the callback function provided to the LocalStrategy
object is the one that contains the logic used to verify a user’s identity.
The verify callback must return a model of the user when the authentication is successful (the credentials are valid).
In our case it is a mongoose model of the User
that will be returned. How this model is constructed will be covered once we discuss the passport-local-mongoose package.
Once a strategy has been supplied, the relevant middleware has to be configured with Express so our web server can use passport. In an app.js
file, it generally looks like the following:
const session = require("express-session"); app.use(session({ secret: "cats" })); app.use(express.urlencoded({ extended: true })); // express body-parser app.use(passport.initialize()); app.use(passport.session());
The order of these statements are important, so keep that in mind.
Using Sessions with Passport
For supporting sessions, passport has to be added as a middleware to the login route or endpoint that you are using to authenticate your users, usually with the redirect route values for your application:
// Use the passport middleware for authentication app.post('/login', passport.authenticate('local', { successRedirect: '/dashboard', failureRedirect: '/login' }));
When a POST request with the user’s login information is made to the '/login'
route, passport uses the local
authentication strategy to verify that the user’s credentials are valid.
It then serializes the provided User
model into one value that is stored in the session
object provided by express-session.
When future requests from the same user are made with the session cookie, passport uses the serialized session
value to deserialize or retrieve the User
model.
This User
object is made available through the request.user
property.
In this way, passport builds upon the functionality provided by the express-session package.
passport-local-mongoose
passport-local-mongoose takes care of salting and hashing user passwords, serializing and deserializing your user model (for session storage), and authenticating the username and password credentials with their stored counterparts in the mongo database.
It is a mongoose plugin first and foremost. It uses the passport-local module internally to provide and configure a LocalStrategy
of local authentication for the passport module.
Before using this package make sure that you are using mongoose and are connected to a mongod
instance in your app.
In app.js
add the following require statement:
const passportLocalMongoose = require('passport-local-mongoose');
In our model class user.js
:
const mongoose = require('mongoose'), passportLocalMongoose = require('passport-local-mongoose'); const UserSchema = new mongoose.Schema({}); UserSchema.plugin(passportLocalMongoose); module.exports = mongoose.model('User', UserSchema);
The line UserSchema.plugin(passportLocalMongoose)
is responsible for extending the model object.
According to the package documentation:
You’re free to define your User how you like. Passport-Local Mongoose will add a username, hash and salt field to store the username, the hashed password and the salt value.
Additionally Passport-Local Mongoose adds some methods to your Schema. See the API Documentation section for more details.
In app.js
you add some configuration code for passport:
// requires the model with Passport-Local Mongoose plugged in const User = require('./models/user'); // USE "createStrategy" INSTEAD OF "authenticate" // This uses and configures passport-local behind the scenes passport.use(User.createStrategy()); // use static serialize and deserialize of model for passport session support passport.serializeUser(User.serializeUser()); passport.deserializeUser(User.deserializeUser());
passport-local-mongoose
serializes and deserializes model objects based on the username
field, so it should be unique to every model.
If mongoose is connected to mongod, this should be all the configuration code needed to use the passport-local-mongoose
plugin.
To create a User
, we can use the register
method added by this plugin:
app.post('/register', (request, response) => { // Creates and saves a new user with a salt and hashed password User.register(new User({username: request.body.username}), request.body.password, function(err, user) { if (err) { console.log(err); return response.render('register'); } else { passport.authenticate('local')(request, response, function() { response.redirect('/dashboard'); }); } }); });
Now, when a User
is created and stored in the database, this is how it will be stored, as displayed in the mongo shell:
> show collections users > db.users.find() { "_id" : ObjectId("5aea739b999c1e703ca7f093"), "username" : "user", "salt" : "2b3721324daf1f22a0f93cd70ce9bf55c2edad2ee5abaed5eb7e56485bc331af", "hash" : "8fa16f7c0fa2446bac5cb2236dd9d0f4cbd0e555e823b4c45476b1a0e77b5f04e388a7b8e2191fab68dc48edc71c58fa698e626d600e52fb0961722279ee1ec2f3be15b7952a6698484c750a96c91377620542a8588b2c768a1e183cb549a452d68a3130541eed1b6bc03f226d1212441d50f49274d568315166087a3940535db0c3868763c95834edb211d985ca3aa38326cbe02ddfc7a48e043068d9f53e1d969c4b215830e95f306f4f6df8b2de0b51ddac499ddc39ede61744161a1e6b281de067ad5732d6fbc85946b7e7919955656a72e301121e3af4cd12630f3cfb0dc2a2ddf35c1d3417c269ac0b045e8f78f7b607e1cdaeaa61b722dedb6bb1ba86f0a3c16632c64f3a67bd118d4efe5bca7368f02d26e352c93ad28a054a6d792b56e33a436a8adf2f57305bf70f8d52019ff466e6f7f02d7672b69900a4ca98ce5c81290bbdd855a4b4cb533e1056d22c695a5b01ce7add3a3b39696b7bc7194e6792082da3cee3aed9070a1882a72e61229d5a1f4b0df1d64358b7bd849a4d682db4ebc5bf9dd4ae047741b8b2f2446c200bbd6f6954ef0b18d93816aa1ea8ed2bb4d95aa517f2bc09eec10ba7e15ea216dfd111759da9bd5fb567cf9df4253cc5b120e55d53278580318b0435d16a98b56c09f9907b00d79d9f1352377db7be4f494ee49235fc35cfc02e4f031b68665078f9fe415d8e9727b180f593d8663d", "__v" : 0 }
Your User
object is now available through request.user
in an express app
route callback after the user has been authenticated by passport.
passport-local-mongoose does not store the password
, hash
, and salt
fields in the request.user
object, however, out of safety concerns.
Making Your Own Middleware
After a user has been authenticated with passport in a session, you can use the isAuthenticated()
method in the request
object to determine if the user is logged in or not.
You can use this to make your own middleware for verifying if the user is logged in before accessing a certain route:
function isLoggedIn(request, response, next) { // passport adds this to the request object if (request.isAuthenticated()) { return next(); } response.redirect('/login'); }
And here it is in action:
app.get('/dashboard', isLoggedIn, (request, response) => { // dashboard logic });
Logging Out
Passport includes a logout()
function on request
that can be called from a route handler. It removes the request.user
property and clears the login session.
app.get('/logout', (request, response) => { request.logout(); response.redirect('/'); });
Surprised I am the first one to comment on this. Great read, thank you for writing it. I now have a much better understanding of these packages and how / why they are used!
LikeLike
I’m glad I could help! Have fun building stuff (-:
LikeLike
Hi Damian,
What request should I send to the server to recognize me.
For example i’m logging in and i’m receiving a token, then how to include that token in the headers?
Moreover where is this token?
Is it attached in the user object when i return this function -> return done(null, user); ?
The question might be stupid but I’ve been trying to solve the problem for two weeks now.
Thank you in advance.
LikeLike
Hi Vasil!
Are you doing session-based authentication or token-based authentication?
Here’s a brief article that explains the differences: https://medium.com/@sherryhsu/session-vs-token-based-authentication-11a6c5ac45e4
If you’re doing session based auth with Express using the same packages as the article, then you can view the session ID by:
“You can view the value of this ID in action by logging request.sessionID when inside an Express route callback.”
You can also inspect the HTTP requests in your browser using the development tools. This will allow you to view the headers.
I hope that helps!
LikeLike
Great article! It makes much more sense now. Thank you very much!
LikeLike
I’m glad I could help!
LikeLike
Can you explain more about the serialize method? I’m not able to understand what it actually does. Also, what is the difference between User.searializeUser() and passport.serializeUser() and why is the former one passed as an argument to the latter one?
LikeLike
Hey Damian,
Thanks, this article does make things a little clearer.
I am a little unclear on what this line does, however,
passport.authenticate(‘local’)(request, response, function() {
response.redirect(‘/dashboard’);
});
as it doesn’t match the syntax I’ve seen used in the docs, which is usually
passport.authenticate(strategyName[, options][, callback])
LikeLike
The explanation that I needed for months!! Thank you!!
LikeLike
Thank you so much for this great work! I was struggling for days to do this.
LikeLike
Hey Damian , Great article man ! I got basic idea about passport and passport-local and ,I have also used this concepts in my project.I have created website where two types users(user and admin) are allowed to logged in.
But I am unable to create two separate session for this two user. can you just explains how to maintain two session in one app?
LikeLike
Hi Varun, I’m glad you found the article helpful!
I would look into “authorization” for your user session, where you can use roles (like “user” or “admin”) to authorize routes, pages, and resources for your web application!
These could be implemented as easily as properties in your User object, and you can write middleware that makes use of these to implement application-wide authorization!
LikeLike
Saved as a favorite!, I really like your site!
LikeLike
Hi Adams,
Thanks for the detailed post about this beautiful blog. It’s really helpful.
I am using the express-session module and have all the required setup.
Session Middles ware
***********
app.use(
session({
secret: ‘my secret’,
resave: false,
saveUninitialized: false,
})
);
**************************
Then in a post middle ware
app.post(‘/registered-user/:email’, (req, res, next) => {
req.session.isLoggedIn = true;
****************************
As session data should persist across the request, when I try to get the session object logged, i don’t see this value persists. Also, as you have mentioned in the blog that there a session ID is created per user, how can we get access to the ID.
NOTE:-
The post request is made from a React Component.
Appreciate your help!
Thanks!
LikeLike