微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

node.js – Passport本地策略完成回调并不通过错误json消息

我试图在身份验证失败时传递 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('/',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"
  }
}

我究竟做错了什么?

解决方法

您设置的消息值存储在会话和闪存中.我不认为护照有任何选择发送json错误消息.但是您可以在身份验证方法中传回回调,并从中发送消息:

app.post('/login',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,next);   
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐