Building Authentication with passport.js Chapter 6
Introduction to passport.js
passport.js is a middleware provided by Node.js for authentication. The functionality of
passport.js is to authenticate the requests that are made to the server. It provides several
strategies for authentication. passport.js provides strategies to such as local strategy,
Facebook strategy, Google strategy, Twitter strategy, and JWT strategy. In this chapter, we
will focus on using the JWT strategy.
JWT
JWT is a way of authenticating the requests using a token-based approach. There are two
methods of authenticating requests: cookie-based authentication, and token-based
authentication. The cookie-based authentication mechanism saves the user's session ID in
the browser's cookie, whereas the token-based mechanism uses a signed token that will
look like this:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVhNjhhNDMzMDJkMWNlZDU5YjExND
g3MCIsImlhdCI6MTUxNzI0MjM1M30.5xY59iTIjpt9ukDmxseNAGbOdz6weWL1drJkeQzoO3M
This token is then validated on every request that we make to the controllers.
For our application, we will use a combination of both. When a user requests to log in to the
app, we will create a signed token for them and then add that token to the browser's cookie.
The next time when the user logs in, we will read that token from the cookie and validate
that token using the passport-jwt module in the server, and then decide whether or not
to log that user in.
If you look at the preceding token carefully, you will see that the token has three parts
separated by a period (.); each part has its own meaning:
The first part represents the header
The second part represents the payload
The third part represents the signature
To be able to use this JWT, we will need to add a package. To do that, we can just run the
following command:
$ npm install jsonwebtoken --save