Howto prevent www-authenticate header when using passport-http Basic + passport-local combination

Hi, I want to support both standard and basic authentication in my application. Everything works as expected, except when I use auth through a form using angularjs with the wrong credentials.

Instead of having my angular code process 401, the browser displays the BASIC auth dialog called by the WWW-Authenticate header.

How can I prevent this header from being added when using the local strategy? Or how can I support both mechanisms differently?

I use the following route in my express application.

api.post('/authenticate', passport.authenticate(['local', 'basic'], { session: false }), function (req, res) { 

This allows you to use both authentication methods at this URL. I repeat, when I use the wrong credentials using formbased, it shows me the basic auth dialog (I don't want this).

This is how I registered the strategies.

 passport.use(new BasicStrategy({ realm: 'Authentication failed. Wrong username or password.'}, verifyLocalUser)); passport.use(new LocalStrategy(verifyLocalUser)); 

This is how my verifyUser method looks like ...

 var verifyLocalUser = function (username, password, next) { User.findOne({ username: username }).select('fullname admin username password').exec(function (err, user) { if (err) { return next(err); } if (user && user.comparePasswords(password)) { return next(null, user); } else { next(null, false, { message: 'Authentication failed. Wrong username or password.' }); } }); } 

Does anyone know how to support multiple authentication methods using a .js passport?

For completeness, this is angular code that authenticates me ...

 authFactory.signIn = function (username, password) { return $http.post('/api/authenticate', { username: username, password: password }).then(function (res) { AuthToken.setToken(res.data.token); return res.data; }, function (res) { console.warn(res); }); }; 
+5
source share
1 answer

instead of this:

 next(null, false, { message: 'Authentication failed. Wrong username or password.' }); 

You can use this:

 cb(new YourCustomError()) 

And "YourCustomError" may have a message, for me, my "YourCustomError" looks like this:

 class HttpError extends Error { constructor (msg = 'Invalid Request', status = 400) { super(msg) this.status = status } } class Forbidden extends HttpError { constructor (msg = 'Forbidden') { super(msg, 403) } } 

Or maybe new Error(<message>) will work correctly for you, too

0
source

All Articles