mikenicholson / passport-jwt

Passport authentication using JSON Web Tokens
MIT License
1.96k stars 213 forks source link

passport.authenticate('jwt', ... ) does not give any response #221

Open Harshal96 opened 3 years ago

Harshal96 commented 3 years ago

Strategy:

passport.use('jwt', new JWTstrategy({
    secretOrKey: 'secret',
    jwtFromRequest: ExtractJWT.fromExtractors([ExtractJWT.fromAuthHeaderAsBearerToken(),
                                               ExtractJWT.fromUrlQueryParameter('token'),
                                               ExtractJWT.fromBodyField('token')])
}, (jwt_payload, done) => {
    User.findOne({id: jwt_payload.sub}, function (err, user) {
        done(err, user, {});
    });
}));

JWT signing:

const body = {_id: user._id, email: user.email};
const token = jwt.sign({user: body}, 'secret');

Authentication:

passport.authenticate('jwt', { session: false}, async (err, user, info) => {
    console.log(err, user, info);
});

When running with Postman, I selected Authorization as "bearer token" and simply pasted the token in the box. I also tried sending it as a query parameter and in the request body.

Nothing works. There is no error, it just doesn't give any response.

tontonel commented 3 years ago

same problem!

StephanBijzitter commented 2 years ago

Yeah this one took me a while too... the callback (in OP defined as (jwt_payload, done) must not be asynchronous in any way. Change that to (jwt_payload, done) => done(null, jwt_payload).

Then, the authenticate function needs to be wrapped:

    const authenticateWithJwt = (req, res, next) => {
        passport.authenticate('jwt', {session: false}, (error, jwt_payload) => {
            if (error) {
                return next(error);
            }

            User.findOne({id: jwt_payload.sub}, (err, user) => {
                if (err || !user) {
                    return next(err || new Error('Could not find user'));
                }

                next(user);
            });
        })(req, res);
    };

    app.get('/protected', authenticateWithJwt, (req, res) => {
        res.status(200).json({message: 'it works!'});
    });