Friday 2 June 2017

json web tokens, passport-jwt and its verify function

I've been doing some research on json web tokens recently. From what i've gathered, one of its great strengths is that its stateless. Everything you need to authenticate the user comes with the request, therefore you don't need to "hit the database on every request" as many articles state.

However, if i'm not mistaken, the docs for passport-jwt do just that, they hit the database on each request. That is, for each request that requires passport authentication.

passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
    //this is a database call
    User.findOne({id: jwt_payload.sub}, function(err, user) {
        if (err) {
            return done(err, false);
        }
        if (user) {
            done(null, user);
        } else {
            done(null, false);
            // or you could create a new account 
        }
    });
}));

I was under the impression that by the time this function is called, the token has already been verified, otherwise this function would not be called and the user gets a 401 unauthorized.

So why check the database for the user? Since this code is in the docs, i'm doing the same thing by checking the database, but do i really need to? Why shouldn't i just do this

passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
    //this is a database call
    done(null, {id: jwt_payload.sub})
}));



via Eric Guan

No comments:

Post a Comment