Git Product home page Git Product logo

Comments (8)

olee avatar olee commented on July 24, 2024 11

I used the following middleware to handle at least the situation when mixed authorized and unauthorized access is desired.

    app.use((req, res, next) => {
        passport.authenticate('jwt', { session: false }, (error, user, info, status) => {
            if (user === false && info && info.message === 'No auth token') {
                // Just unauthorized - nothing serious, so continue normally
                return next();
            }
            return unauthenticatedError(res);
        })(req, res, next);
    });

And at some later point I use this custom middleware to protect all following routes

function isAuthenticatedMiddleware(req, res, next) {
    if (req.isAuthenticated())
        return next();
    res.statusCode = 401;
    res.json({
        message: http.STATUS_CODES[res.statusCode]
    });
};

from passport-jwt.

geyang avatar geyang commented on July 24, 2024

Hi,

I just forked this repo and got it to work.

In my fork, I defer all error handling to the self._verify function so that users can handle

  • missing authentication token
  • invalid tokens with jwt_errors by themselves.

These lead to a change in the contract of the self._verify function, which becomes:

function (req, jwt_error, jwt_token, authorize)
or 
function (jwt_error, jwt_token, authorize)

also, I want to allow the authorize call back to not throw an error when the user is missing, because my subsequent middlewares use the req.user object when it exists, but it is not required.

If you are interested in these I can fix the tests and submit a PR. If not, it's okay.

Thanks for this module!

from passport-jwt.

darth-cheney avatar darth-cheney commented on July 24, 2024

I have to second what @episodeyang is talking about here. Right now, the strategy obfuscates errors that come built in with jsonwebtoken, upon which the strategy is based. Those implementing this strategy cannot send errors that are present in the jsonwebtoken module nor can they even inspect them.

The verify callback should absolutely include any errors that occurred underneath.

from passport-jwt.

vmehera123 avatar vmehera123 commented on July 24, 2024

pls help. got 401 Unauthorized, when trying get secure /api.

APP.JS

opts.secretOrKey = app.get("superSecret");

passport.use(new JwtStrategy(opts, function (jwt_payload, done) {
  User.findOne({email: jwt_payload.email}, function(err, user) {
    if (err) {
      return done(err, false);
    }
    if (user) {
      done(null, user);
    } else {
      done(null, false);
      // or you could create a new account
    }
  });
}));
app.use(passport.initialize());
app.use("/api", passport.authenticate("jwt", {session: false}));

/API/LOGIN that generate token

function loginHandler(req, res, next) {
  User.findOne({email: req.body.email}, function (err, user) {
    return res.json({
      token: jwt.sign({email: user.email}, req.app.get("superSecret"), {expiresIn: 120})
    });
}

so, my REQ.HEADERS:

{
authorization: "token12312j3jkbskjfskjfbsjkdfnksjdnf"
}

what i'm missing? why i'm got 401 Unauthorized if there are token in req.headers?

from passport-jwt.

rajaraodv avatar rajaraodv commented on July 24, 2024

+1

from passport-jwt.

thaiat avatar thaiat commented on July 24, 2024

+1

from passport-jwt.

randiguarcas avatar randiguarcas commented on July 24, 2024

var token = jwt.sign({ user: User.id }, config.secret,{
expiresIn: (1*60),
algorithm: 'HS256'
});

res.json({success: true, APIToken: "JWT " + token});

send request Header : JWT TOKEN_GENERATE

from passport-jwt.

mikenicholson avatar mikenicholson commented on July 24, 2024

I know this is an old issue, I think what you are looking for is the custom callback feature of passport. That is where you handle failed authentication, JWT parse errors, etc. See http://passportjs.org/docs#custom-callback

Your custom callback would have the signature:

function (err, user, info) { .... }

If a JWT parse error occurs or the JWT is not valid the user will be false and info will contain the error that jsonwebtoken provides explaining why validation of the JWT failed.

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.