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

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.

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 19
  • Comments: 35 (1 by maintainers)

Most upvoted comments

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>

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

Hi @kittrCZ , It didn’t work for the dummy project I was practicing but then in the main project, all I did was changed the opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken(); to: opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('JWT');

Also if you’re logging in the user, you must be using jwt.sign() to generate the token. After this step you’re probably either storing the token somewhere or you’re sending the token in response. Make sure that you’re sending as such token: 'JWT ' + token I think using lowercase jwt causes problems sometimes.

I don’t know if this will work but that’s all the change I could see in my previous code and earlier code. So it boils down to three things :

  • Check the extractor you are using. Sometimes weird discrepancies occur there

  • Check if you’re appending the token with ‘JWT’ and not ‘jwt’

  • There could also be a version issue. Check the version of passport-jwt, passport and jsonwebtoken for any changes or incompatibility

Let’s discuss if you’re still running into the same problem.

Thanks

so I figured out yesterday. The token was truly expired. I highly recommend to everyone to create a testing endpoint with jwt.verify().

This issue ca be closed

You have to return “Bearer + token” and not “JWT + token”. Add bearer “token” in Authorization value

@theakshaygupta no totally nothing. Everything gets instant 401 response

Hi all, i’m still having this challenge after verification using jwt.verify(), token was successfully verified. Strangely, it didnt work let opts = {} opts.jwtFromRequest = req.headers.authorization.split(’ ')[1]; opts.secretOrKey = process.env.JWT_TOKEN; opts.ignoreExpiration = true;

 passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
  
      console.log('Now in middleware' ); //Not logging
      User.findOne({_id: jwt_payload._id}, function(err, user) {
          if (err) {
          
              return done(err, false);
          }
          if (user) {
              return done(null, user);
          } else {
              return done(null, false);
          }
      });
  }));
 First, i have to fetch the token using a different method. Also, could someone tell me why i can't console.log in passport.use(...{...}).

Digging further, i did let pass = passport.use(… console.log(pass); and i got this

{“_key”:“passport”,“_strategies”:{“session”:{“name”:“session”},“jwt”:{“name”:“jwt”,“_jwtFromRequest”:“eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1YjFkNmQwMWI5N2YxMTAxZDU4MDY1MmQiLCJmaXJzdE5hbWUiOiJoZWxvbyIsInJvbGUiOlsiUGF0aWVudCJdLCJleHAiOjE1Mjk0MDYxMjIsInNlY3JldE9yS2V5IjoiUkVTVEZVTEFQSXMiLCJpYXQiOjE1Mjg4MDEzMjJ9.KTminBQ8Mzi7IuKsjKjtWPSvYWevqHRW”,“_verifOpts”:{“ignoreExpiration”:true}}},“_serializers”:[null],“_deserializers”:[],“_infoTransformers”:[],“_framework”:{},“_userProperty”:“user”,“_sm”:{“_key”:“passport”},“strategies”:{}}

It actually got the data. Not really sure what is going on at this point again.