Git Product home page Git Product logo

Comments (11)

azharuniverse avatar azharuniverse commented on July 4, 2024 3

You can check for Error string in info to catch and provide custom messages.

passport.authenticate('jwt', (error, user, info) => {
    sails.log.info('isAuthenticated policy: ', error, user, info.name);

    if (info.name === 'TokenExpiredError') info.status = 401;
    if (info.name === 'JsonWebTokenError') info.status = 401;
    if (info.name === 'Error') info.status = 401;
    if (error || !user) return res.negotiate(error || info);

    req.user = user;
    next();

  })(req, res);

from passport-jwt.

mikenicholson avatar mikenicholson commented on July 4, 2024

I think you're looking for the Custom Callback functionality of the Passport module.

from passport-jwt.

rkt2spc avatar rkt2spc commented on July 4, 2024

Sure, I can go and check if the authorization header exists before triggering the passport middleware. But why don't we put it into the strategy extraction method itself? Something like:
jwtFromRequest: ExtractJwt.fromAuthHeader({failmessage: 'missing token'})

from passport-jwt.

mikenicholson avatar mikenicholson commented on July 4, 2024

This is not the point of the extractor function and a violation of single responsibility pattern. The extractor function is only responsible for extracting the JWT from the request if it exists.

There is no need to check the request for the authorization header before triggering passport. The decision of what to do if the JWT is missing takes places in the strategy's authenticate() method.. Right now it returns a generic error which you can then catch and handle in the custom callback register via passports Custom Callback functionality.

That is where I recommend providing the custom error response.

The potential improvements I see in this area are:

  1. Return a custom error class to make it easier to identify when the JWT was missing.
  2. Do something like passport-local and provide a custom error message via the Strategy constructors generic options argument.

from passport-jwt.

mikenicholson avatar mikenicholson commented on July 4, 2024

Let me know if this covers your use case. If you have a suggestion I am open to pull requests or we can create a feature request to address the need.

Thanks for using the module and I appreciate any feedback!.

from passport-jwt.

mikenicholson avatar mikenicholson commented on July 4, 2024

Haven't heard anything in a few days. Closing for now.

from passport-jwt.

GeekEdem avatar GeekEdem commented on July 4, 2024

Hello. Cannot understand how to set custom error message for different errors and how can I embed JWT black list to this strategy? Thanks for answer

from passport-jwt.

mikenicholson avatar mikenicholson commented on July 4, 2024

@GeekEdem Sorry to sound like a broken record but handling custom error messages is explained here: http://passportjs.org/docs#custom-callback

and if you want to blacklist JWTs you can put that logic into the verify callback when constructing the strategy

passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
       if ( is_jwt_blacklisted(jwt_payload) ) {
            return done(err, false);
        }
        else  { 
            // jWT is not blacklisted, look up a user or
           // whatever else you were planning on doing with a
          // valid JWT
        } 
    });

note that is_jwt_blacklisted is just a funciton I made up. You'll have to supply that function as the strategy doesn't maintain a blackisted jwt list on its own.

from passport-jwt.

GeekEdem avatar GeekEdem commented on July 4, 2024

@themikenicholson Here is my solution, if someone need)

function requireAuth (req, res, next){
    passport.authenticate('jwt', jwtSession, function (error, decryptToken, jwtError) {
        if(typeof (jwtError) === 'object'){
            return general.response(res, {
                field: 'Authorization',
                location: 'header',
                messages: [
                    jwtError.message
                ]
            });
        } else if (!error) {
            let token = req.header('Authorization').slice(4);
            TokenModel.findOne({token: token}).lean().exec( (err, result) => {
                if(!err && !result) {
                    req.user = decryptToken;
                    return next();
                } else if (!err && result) general.response(res, {
                    field: 'Authorization',
                    location: 'header',
                    messages: [
                        'token is in black list'
                    ]
                });
                else general.response(res, err);
            });
        }
    })(req, res, next);
}

this method I use as middleware in express.
general.response - this is method, that make response message and return them.
TokenModel - this is mongoose model, to check is token in blacklist collection in MongoDB.

from passport-jwt.

rkt2spc avatar rkt2spc commented on July 4, 2024

@themikenicholson
Following the passport custom-callback

router.get('/jwt', (req, res, next) => {

    passport.authenticate('jwt', (err, user, info) => {

        if (err) return next(err); // It is null
        if (!user) return res.status(403).json(info);
        res.status(200).json(user);

    })(req, res, next);
});

If token extraction failed, the custom error is placed in the "info" parameter. Is this by design? Shouldn't it be at the "err" parameter?

Update: I will continue with Issue #75

from passport-jwt.

mrtnzagustin avatar mrtnzagustin commented on July 4, 2024

Manteiners should add this "info" param and examples to the http://www.passportjs.org/packages/passport-jwt/ docs. I could't find the error until i read this issue. Thanks

from passport-jwt.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.