Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passport Serialization and Deserialization Vs JWT

I am using passport-local, passport-jwt module for authentication strategy in my application. I am trying to understand would I still need to use passport.serialize() and passport.deserialize() methods. As far as I understand these methods uses sessions to store user info. I suspect that purpose of using these methods is already fulfilled using JwtStrategy. Or I am completely wrong here ?

I tried looking over web but couldn't get much information there.

Here is my code for the JWT strategy

router.get('/current', passport.authenticate('jwt', {session: false}), (req, res) => {
  res.json({
    id: req.user.id,
    email: req.user.email,
    first_name: req.user.first_name,
    last_name: req.user.last_name,
  });
})

Please correct me if I am wrong about my assumption.

like image 303
Roshan Avatar asked Feb 27 '26 07:02

Roshan


1 Answers

JWT strategy is used here.

passport.authenticate('jwt', {session: false})

This code is middleware which takes the token key from Authorization of request headers and then check the token key if correct and fires passport.use(new JwtStrategy(opts, (jwt_payload, done) method.

Then, your code ( I supposed just like this ) :

passport.serializeUser(function (user, done) {
    done(null, user);
});

passport.deserializeUser(function (user, done) {
    done(null, user);
});

// jwt
let opts = {
    jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('jwt'),
    secretOrKey: "secret"
};

passport.use(new JwtStrategy(opts, (jwt_payload, done) => {

    UserRepository.get_user_by_id(jwt_payload.user.id, (err, user) => {
        if (err) {
            return done(err, false);
        }
        if (user) {
            return done(null, UserRepository.set_existing_user_for_token_key(user));
        } else {
            return done(null, false);
        }
    });
}));

Returns a user, then it serializes to json when you can use in router.get (or another method) function.

like image 138
canmustu Avatar answered Mar 02 '26 16:03

canmustu