question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Passport authentication with JWTStrategy not working - Error: Could not get a response

See original GitHub issue

Hello, I was trying to authenticate with passport JWTStrategy

passport-oauth.js :

const passport = require('passport');
const JwtStrategy = require('passport-jwt').Strategy,
    ExtractJwt = require('passport-jwt').ExtractJwt;

const oauth = require('../oauth/oauth_credentials');
const User = require('../models/user');

var opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = require('./jwt').secret;

console.log('Obviously control comes here');
passport.use(new JwtStrategy(opts, function (jwt_payload, done) {
    console.log('Control never comes here');
    User.findOne({ _id: jwt_payload.sub }, function (err, user) {
        if (err) {
            return done(err, false);
        }
        if (user) {
            return done(null, user);
        } else {
            return done(null, false);
        }
    });
}));

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

If you see my two console.log() functions, the control never comes to passport.use(new JWTStrategy…

I am authenticating here :

router.post('/test', passport.authenticate('jwt', { session: false }), (req, res) => {
    res.send('Authenticated');
});

I used postman to send my request :
screen shot 2018-03-26 at 11 48 07 pm

As you can see I provided the authentication header too , and I am getting this error Could not get a response . If anyone could please tell me what’s wrong, I’ve been at it since hours.

Thanks.

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:18
  • Comments:33 (1 by maintainers)

github_iconTop GitHub Comments

11reactions
mohammadalijfcommented, Sep 8, 2018

hey guys, i had the same problem and solved the problem by writing a little middleware

// passport.js
passport.use(new JWTStrategy({
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: process.env.SERVERSECRET
}, (token, done) => {
    return done(null, token);
}));

// router/index.js

/**
 * middleware for checking authorization with jwt
 */
function authorized(request, response, next) {
    passport.authenticate('jwt', { session: false, }, async (error, token) => {
        if (error || !token) {
            response.status(401).json({ message: 'Unauthorized' });
        } 
        try {
            const user = await User.findOne({
                where: { id: token.id },
            });
            request.user = user;
        } catch (error) {
            next(error);
        }
        next();
    })(request, response, next);   
}

router.use('/user', authorized, userRouter);
// router/user.js

router.get('/', (request, response, next) => {
    response.send(request.user);
});

and in my request i had to set Authorization: bearer <token>

11reactions
akshaydotshcommented, May 24, 2018

I assume your console.log(jwtPayload) is not printing anything ?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Where did I go wrong with passport-jwt setup? - Stack Overflow
I pass token as value of Authorization header in get request on the home page, but it did not help. This is the...
Read more >
The Ultimate Guide to Passport JS - Zach Gollwitzer
In this post, I am going to walk through why the Passport-JWT authentication strategy is a simple, secure solution for small teams and...
Read more >
Nest.js Step-by-Step: Part 3 (Users and Authentication)
Use Nest.js in a User's Module create a user and locate them in the database, and shows how to add the Auth Module...
Read more >
API with NestJS #3. Authenticating users with bcrypt, Passport ...
Authenticating users with bcrypt, Passport, JWT, and cookies; 4. ... It indicates that there should not be two users with the same email....
Read more >
User Authentication in Web Apps (Passport.js, Node, Express)
In this full course for beginners, you will learn how to implement user authentication from scratch in your web apps. You will learn...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found