I am trying to pass a JSON message when authentication fails, using done callback in the LocalStrategy, but all I get is 401 and "Unauthorized" string in the response.
var express = require('express');
var bodyParser = require('body-parser');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var app = express();
app.use(bodyParser.json());
app.use(passport.initialize());
passport.serializeUser(function(user, done) {
done(null, user.email);
});
var strategy = new LocalStrategy({ usernameField: 'email' },
function (email, password, done) {
if (email === '[email protected]' && password === 'pass') {
return done(null, { email: '[email protected]' });
} else {
// never get this json object on the client side when posting invalid credentials
return done(null, false, { message: 'invalid email or password' });
}
}
);
passport.use(strategy);
app.post('/login', passport.authenticate('local'), function(req, res) {
console.log(req.user);
res.json(req.user);
});
app.get('/', function(req, res) {
res.json({ message: 'hello!' });
});
var server = app.listen(3000, function() {
console.log('api is listening on ', server.address().port);
});
package.json
{
"name": "passport_example",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.13.3",
"express": "^4.13.3",
"passport": "^0.2.2",
"passport-local": "^1.0.0"
}
}
What am I doing wrong?
The message
value you are setting is stored in session and flash. I don't think passport has any option to send json error message. But you can pass a callback in authenticate
method and send message from there:
app.post('/login', function(req, res, next ){
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err) }
if (!user) { return res.json( { message: info.message }) }
res.json(user);
})(req, res, next);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With