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();
});
});
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.
Most helpful comment
Nevermind, found the solution: