Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Harshal96 opened this issue Oct 23, 2020 · 2 comments
Open

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

Harshal96 opened this issue Oct 23, 2020 · 2 comments

Comments

@Harshal96
Copy link

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
Copy link

same problem!

@StephanBijzitter
Copy link

StephanBijzitter commented Jul 22, 2021

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!'});
    });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants