bhoriuchi / passport-activedirectory

Active Directory strategy for passport.js
29 stars 16 forks source link

Custom response when credentials are wrong (express) #4

Closed mauromereu closed 7 years ago

mauromereu commented 7 years ago

Hi, I'm using passport-activedirectory in a rest api, to authenticate for token request. When an error occurs, i.e. the password is wrong, it always calls a res.end with the error stack as a message and error code 500. I was able to set the right status (401) in my error managing route in express, but with a workaround:

//error handling
app.use(function(err, req, res, next) {

//here the workaroun
    if (/InvalidCredentialsError/.test(err.stack)) {
      res.status(401);
      return;  // no res.end(mymessage) because it is called by the Strategy,error() of passport-activedirectory
    } 
//end workaround

    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    return res.boom.internal(err.message);
}); 

Is there a way to redefine the Strategy.error() method or to avoid it to call res.end, or set a custom message?

bhoriuchi commented 7 years ago

have you tried using the failWithError option?

app.post('/route/to/auth', Passport.authenticate('ActiveDirectory', { failWithError: true}), function (req, res) {
 ...
}, function (error, req, res, next) {
  var statusCode = /InvalidCredentialsError/.test(error.stack)
    ? 401
    : 500
  return res.status(statusCode).send(error.message)
})
mauromereu commented 7 years ago

This way it works, even without the failWithError option. The key is to define directly in the route the callback for errors.

Thanks!