Passport-http-bearer: Custom handling of response on failure

Created on 1 Jul 2015  路  4Comments  路  Source: jaredhanson/passport-http-bearer

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

Most helpful comment

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

All 4 comments

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

Thanks @carera , I was looking for the same.

What if I want to reuse that middleware?

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mwawrusch picture mwawrusch  路  3Comments

konijn picture konijn  路  3Comments

akshaysrin picture akshaysrin  路  3Comments

danieljack picture danieljack  路  3Comments

juriansluiman picture juriansluiman  路  3Comments