我试图在身份验证失败时传递JSON消息,在LocalStrategy中使用完成回调,但我得到的只是401和"未授权"响应中的字符串。
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 === 'test@gmail.com' && password === 'pass') {
return done(null, { email: 'test@gmail.com' });
} 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"
}
}
我做错了什么?
答案 0 :(得分:21)
您正在设置的message
值存储在会话和闪存中。我不认为护照有任何选项发送json错误消息。但是您可以通过authenticate
方法传递回调并从那里发送消息:
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);
});