Setting Up Passport JWT

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 363:- Setting Up Passport JWT

To set up Passport JWT, we need to install two packages passport and passport-jwt.

bashCopy code

npm install passport passport-jwt

Once we have installed these packages, we can configure Passport to use JWT strategy in our application. The basic steps to configure JWT strategy are as follows:

  1. First, we need to initialize Passport in our application. We can do that by requiring Passport module and invoking the passport.initialize() middleware function in our app.js file.

javascriptCopy code

const passport = require('passport'); // initialize passport app.use(passport.initialize());

  1. Next, we need to create an instance of JWT strategy and configure it using the passport-jwt package. We can do this by passing an options object containing the secret key and JWT token options to the JwtStrategy() constructor.

javascriptCopy code

const JwtStrategy = require('passport-jwt').Strategy; const ExtractJwt = require('passport-jwt').ExtractJwt; // configure jwt strategy const jwtOptions = {  secretOrKey: 'your_secret_key',  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken() }; passport.use(new JwtStrategy(jwtOptions, (jwtPayload, done) => {  // find the user from the token  User.findById(jwtPayload.sub, (err, user) => {    if (err) {      return done(err, false);    }    if (user) {      return done(null, user);    } else {      return done(null, false);    }  }); }));

In the above code, we are using JwtStrategy() constructor to create an instance of JWT strategy. We pass an options object to this constructor that contains the secret key and the options to extract JWT token from the request headers.

The passport-jwt package provides a function called ExtractJwt.fromAuthHeaderAsBearerToken() which extracts the JWT token from the Authorization header of the HTTP request.

The JwtStrategy() constructor also takes a callback function that is executed when a JWT token is verified. This callback function takes two arguments, the JWT payload and the done() function.

We find the user from the database using the user id stored in the JWT payload. If the user is found, we return the user object to the done() function. If there is an error while finding the user or the user is not found, we pass false to the done() function.

  1. We can then protect our routes by adding the passport.authenticate() middleware function to the routes that require authentication.

javascriptCopy code

// protected route app.get('/api/posts', passport.authenticate('jwt', { session: false }), (req, res) => {  res.json({ message: 'This is a protected route.' }); });

In the above code, we have added the passport.authenticate() middleware function to the /api/posts route. This middleware function will first authenticate the user using the JWT strategy and then execute the route handler function.

We pass jwt as the first argument to the passport.authenticate() function to specify that we want to use JWT strategy for authentication. We also pass an options object to this function to disable the session since we are using JWT for stateless authentication.

42. APIs (Making APIs And JWT Authentication)

2 Comments

@niteshguptav63
niteshguptav63 Nov 17, 2024 at 1:39 PM

I am not able to access videos from second class and further. I have already completed first class

@niteshguptav63
niteshguptav63 Nov 16, 2024 at 10:56 AM

When will I get my course?

@admin79
admin79 Nov 17, 2024 at 1:29 PM

Now, Your query was resolved.

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support