jaredhanson / passport-http-bearer

HTTP Bearer authentication strategy for Passport and Node.js.
https://www.passportjs.org/packages/passport-http-bearer/?utm_source=github&utm_medium=referral&utm_campaign=passport-http-bearer&utm_content=about
MIT License
951 stars 142 forks source link

Custom handling of response on failure #35

Closed carera closed 9 years ago

carera commented 9 years ago

Hi, Currently, in case of failure, the passport responds either with 401, or redirect if the "failureRedirect" param is set. Is there a way of creating a custom response? E.g., sending JSON on 401 response?

I need to respond with redirect for regular requests and with something else in case of XHR requests since redirect is not an option in XHR due to CORS

I am trying something like this, but it does not work

  app.all('*', function(req, res, next) {
    return passport.authenticate('bearer', {
      session: false
    }, function(err, user, info) {
      if (err) {
        return next(err);
      }
      if (!user) {
        return res.status(401).send({<some JSON response here>});
      }
      return next();
    });
  });
carera commented 9 years ago

Nevermind, found the solution:

app.all('*', function(req, res, next) {
  return passport.authenticate('bearer', {
    session: false
  }, function(err, user, info) {
    if (err) {
      return next(err);
    }
    if (!user) {
      return res.status(401).send(my_json_object);
    }
    req.user = user;
    return next();
  })(req, res, next);
});
webloem commented 8 years ago

Thanks @carera , I was looking for the same.

notgiorgi commented 7 years ago

What if I want to reuse that middleware?

mk-pmb commented 7 years ago

Try standard code reuse tactics: Name your function, register it by its name, and possibly store it in a module.