Search code examples
node.jsexpressjwtkoapassport.js

Passport-jwt authenticate not working well with node-jwt-simple


I'm using passport-jwt to authenticate some routes and I'm creating my jwts with node-jwt-simple/jwt-simple but facing some difficulties cause it looks like my passport-jwt authenticate middleware is not being called at all.

Here is my

passport-jwt-strategy

const jwtOpts = {
    jwtFromRequest: ExtractJwt.fromHeader('Authorization'),
    secretOrKey: secret,
};

passport.use(new jwtStrategy(jwtOpts, (payload, done) => {

    console.log('payload ', payload.sub);
    User.findById(payload.sub, (err, user) => {
        
        if(err) { return done(err); }

        if(!user) { console.log('didnt find!'); return done(null, false); }

        done(null, user);
    });
}));

which i'm then integrating it over here.

routes file

router.get('/success', 
           passport.authenticate('jwt', {session: false}),
           async (ctx, next) => ctx.body = await "success!");

Here is also the way I make my jwt.

function tokenForUser(user) {
    
    const timeStamp = new Date().getTime;
    return jwt.encode({sub: user._id, iat: timeStamp}, secret);
}

//- Later in signup process

userToSave.save(async(err, user) => {
    
    if(err) { return next(err); }

    const token = await tokenForUser(user);

    next(token);
});


//- If this helps, here is how my secret file looks like.

const secret = "JKAha23ja1ddHdjjf31";

export default secret;

Problem comes, when I hit that route i only get Unauthorized and in the console nothing gets logged out not even the 'payload' key I specified first.

I should also say that I have the token at ctx.request.get('Authorization') (Koa based) i think it's something like req.header('Authorization') with express in all routes.

Also The exact express based problem can be found on the github issues of node-jwt-simple here incase there is any problem with my code samples.

Thank you.


Solution

  • After I wrapped my head right i knew that this has been my horrible understanding of how the whole authentification process works.

    When I decoded the token from ctx.get('Authorization') I got a different _id than the one stored in the db Because I had hardcoded Authorization header in postman and thought "If I ctx.set('Authorization', token); It will replace the one I hardcoded on postman".

    Less did I think that this jwt will be included in a header of requests when I make http calls on front end.

    I naively thought jwts are passed directly from the server to the browser (Something like how render works) and Not from the server to an ajax process which later embeds it in request made which is the correct way.

    The whole code is awesome, except now I have to just pass the token ctx.body = token; after I created it when I signed up.

    Thank You.