'Passport JWT - Unauthorized

I'm having a problem where its always returning unauthorized for me. When i set the header Authorization to the token that received. It returns back with.

Unauthorized

.

router.get('/dashboard', passport.authenticate('jwt', {session: false}), (req, res) => {

    res.json('It worked: User ID is: ' + req.user._id);

});

.

var jwtOptions = {

    jwtFromRequest: ExtractJwt.fromAuthHeader(),
    secretOrKey: config.jwt.secretOrKey
    //issuer: config.jwt.issuer,
    //audience: config.jwt.audience,
};

passport.use(new JWTStrategy(jwtOptions, (jwt_payload, done) => {

    User.findOne({id: jwt_payload.id}, (err, user) => {

        if (err) {
            return done(err, false);
        }

        if (!user) {
            return done(null, false);
        }

        return done(null, user);

    });

}));


Solution 1:[1]

You have to change these things:

1) You have to change jwtFromRequest: ExtractJwt.fromAuthHeader(), to jwtFromRequest :ExtractJwt.fromAuthHeaderAsBearerToken(),

2) Set the header: Authorization:Bearer {token}

3) jwt_payload._id change to jwt_payload._doc._id

Solution 2:[2]

I was experiencing the same problem! The code below worked for me.

module.exports = function(passport) {
    passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
        User.findById(jwt_payload._id, function(err, user) {
            if (err) {
                return done(err, false);
            }
            if (user) {
                done(null, user);
            } else {
                done(null, false);
            }
        });
    }));
};

The problem lies with User.findOne({id: jwt_payload.id}, ...

Also while attaching the token to the header use the 'beforeSend' in the AJAX call in this format:

$.ajax({
        url:  url,
        type: 'POST',
        data: data,
        beforeSend: function(xhr) {
          xhr.setRequestHeader('Authorization', window.localStorage.getItem('token'));
        },
        success: function(data) {
          console.log(data);
        },
        error: console.log("Error");
});

Solution 3:[3]

You probably must have made a mistake in the request header. As per the README, it should be 'Authorization' = 'bearer token_received_on_login'

Solution 4:[4]

Just one change needed, use jwt_payload._doc.id instead of jwt_payload.id

Solution 5:[5]

  1. Set the header from res.json({token: 'JWT ' + token}) to res.json({token: 'Bearer ' + token})

  2. jwt_payload.data._id worked for me

Solution 6:[6]

VS code server hangup this will happen because of some mistakes in your code. its not specific to any common code change. It can be any of the small code mistakes done by you. In my case i was using

app.use(express.json)

instead of

app.use(express.json())

Solution 7:[7]

In my case that was not using the same secret value to sign and extract the jwt. After setting the same secret value to both scenarios authentication worked like a charm.

when creating the jwt using jsonwebtoken npm package

const token = jwt.sign(payload, process.env.SECRET, { expiresIn: "1d" })
        return res.status(200).send({
            success: true,
            message: "Logged in successfully!",
            token: "Bearer " + token
        })

When extracting the jwt inside passport

const opts = {
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: process.env.SECRET
};

passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
    console.log("jwt_payload", jwt_payload)
    UserModel.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);
            // or you could create a new account
        }
    });
}));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rahul Gupta
Solution 2 Aᴍɪʀ
Solution 3 Rahul Gupta
Solution 4 Rahul Gupta
Solution 5 richard2k17
Solution 6 Lijo
Solution 7 Lahiru Lanka Rathnayaka