简体   繁体   中英

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);

    });

}));

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

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");
});

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

只需要进行一项更改,使用jwt_payload._doc.id而不是jwt_payload.id

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())

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

In my case: it was the algorithms

const options = {
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  secretOrKey: PUB_KEY,
  algorithms: ['RS256']
};

I removed "algorithms: ['RS256']" and it worked (feeling a bit dum for solving that in 2 hours)

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

  2. jwt_payload.data._id worked for me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM