Doubts on Authentication Techniques - Passport

41 views Asked by At

So I was trying out the authentication techniques with passport and passport-jwt with the express server. Here is the code I've been working with

const JwtStrategy = require("passport-jwt").Strategy;
const ExtractJwt = require("passport-jwt").ExtractJwt;
const User = require("../models/user");
const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = "secret";
module.exports = passport => {
    passport.use(
        new JwtStrategy(opts, (jwt_payload, done) => {
            User.findById(jwt_payload.id,(err,user)=>{
                if(err){
                    return done(err,false);
                }
                if(user){
                    done(null,user);
                }
                else{
                    done(null,false);
                }
            })
        })
    )
};

So the all point of using this passport authorization is to minimize the number of times the database is accessed, right?

But in this code after extracting the token, the database is accessed through the findById method to find whether the user is in the database, so what's the point in all of this if the database is accessed during each authentication request?

I'm pretty sure I'm saying something wrong, some help in clarifying this matter is deeply appreciated.

1

There are 1 answers

1
Owl On BEST ANSWER

The question is, why would you need to do User.findById on the middleware?

You don't have to access the database on the middleware to find whether user exists or not from the JWT payload. When the user is getting the jwt through the /login endpoint, you should've already checked whether the user exists or not

// just a logic example on the login enpoint

const user = User.findUserByEmail(req.body.email);
if (!user) res.sendStatus(401); //returns 401 if user not found
else {
    if (verifyPassword(req.body.password, password)) {
        res.send(generatedJwtWithUserIdOnThePayload)
    } else {
        res.sendStatus(401); //returns 401 if password invalid
    }
}

The jwt that's passed when logging in to the client already had valid user id in it, therefore you dont need to get User document from User.findById everytime client sending a request to your other endpoint.

Since user id is already inside the payload, unless you need other data beside user id from User document, you don't really need to do User.findById on the middleware