Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

    });

}));
like image 281
KayTokyo Avatar asked Sep 05 '16 13:09

KayTokyo


People also ask

Can I use JWT with Passport?

A Passport strategy for authenticating with a JSON Web Token. This module lets you authenticate endpoints using a JSON web token. It is intended to be used to secure RESTful endpoints without sessions.

Which is better Passport or JWT?

JSON Web Token and Passport can be primarily classified as "User Management and Authentication" tools. JSON Web Token and Passport are both open source tools. It seems that Passport with 15.9K GitHub stars and 936 forks on GitHub has more adoption than JSON Web Token with 2.59K GitHub stars and 259 GitHub forks.

What is difference between Passport local and Passport JWT?

passport-local is the strategy you would use if you are authenticating against a username and password stored 'locally' i.e. in the database of your app - 'local' means local to your application server, not local to the end user. passport-jwt is the strategy for using JSON Web Tokens.

What is express JWT?

This module provides Express middleware for validating JWTs (JSON Web Tokens) through the jsonwebtoken module. The decoded JWT payload is available on the request object.


1 Answers

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

like image 128
Nits Avatar answered Oct 12 '22 02:10

Nits