Search code examples
expressjwtpostmanunauthorizedpassport-jwt

cannot access protected route with passport-jwt


I'm not able to authenticate the secret resource, I'm calling with login token still I'm getting unauthorized in response every time.

  passport.use(
  new JwtStrategy(
    {
      jwtFromRequest: ExtractJwt.fromHeader("Authorization"),
      secretOrKey: jwtSecret
    },
    async (payload, done) => {
      try {
        const user = await User.findById(payload.sub);
        console.log(payload.sub);
        if (!user) {
          return done(null, false);
        }
        done(null, user);
      } catch (error) {
        done(error, false);
      }
    }
  )
);

controllers/users.js :

const signToken = user => {
  return jwt.sign(
    {
      iss: "nikname",
      iat: new Date().getTime(),
      sub: user._id,
      exp: new Date().setTime(new Date().getDate() + 1)
    },
    jwtSecret
  );
};

route :

router.route('/secret')
.get(passport.authenticate('jwt',{session: false}),usersController.secret);

I'm not able to figure out the problem since the error is unclear. any help ? Thanks a lot


Solution

  • after using the jwt debugger , it appeared that there was an issue with payload , although the debugger showed a verified token sign, but the 'exp' and 'iat' showed wrong dates, so I changed the signToken constant like this :

        const signToken = user => {
      return jwt.sign(
        {
          iss: "nikname",
          sub: user.id,
        },
        jwtSecret,
        {
          expiresIn: '2d'
        }
      );
    };
    

    also after researching, it appeard that fromHeader (the extractor) is not well functionning in [email protected] so I used fromAuthHeaderWithScheme instead . Like this :

    jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('JWT'),
    

    and now it is working just fine .