One of the great things about using Passport.js is that a lot of the heavy lifting is taken care of by the module. In order to use it, we need to configure it and implement cookies and sessions for persistent logins.
To start using the traditional authentication module, we install the passport
and the passport-local
packages via the terminal:
npm install passport passport-local
Once imported, we require the passport
and passport-local
packages in our JavaScript file:
const passport = require("passport"); const LocalStrategy = require("passport-local").Strategy;
We’re importing the passport-local
package with its Strategy
instance to authenticate users with a username and password.
Now that we have the package installed, we can initialize it by calling the initialize()
method:
app.use(passport.initialize());
passport
is a middleware and must be implemented using app.use()
. The initialize()
method initializes the authentication module across our app.
Next, we want to allow for persistent logins, and we can do this by calling session()
on our passport
module:
app.use(passport.session());
The session()
middleware alters the request object and is able to attach a ‘user’ value that can be retrieved from the session id.
Instructions
Import the passport
library and store it in a const
variable called passport
at the top of the app.js file.
Type node app.js
into the Terminal to start the node app.
Press the Check Work button to check your work for each checkpoint.
Import the passport-local
library with its Strategy
module and store it in a const
variable called LocalStrategy
.
Add the middleware necessary to initialize the passport
library.
Add the middleware to implement a session
with passport
.