护照 – 脸书 – 不能得到about_me和电子邮件configuration文件字段
我正在尝试使用passport-facebook为我的应用程序build立一个login系统。 除了从请求中返回未定义的2个字段之外,一切进展顺利。
我会发布我的整个代码的login程序,因为我没有看到有关它的很多信息,即使在这个问题有很多问题。
这是app.js中的configuration
var passport = require('passport'); var FacebookStrategy = require('passport-facebook').Strategy; passport.serializeUser(function(user, done) { done(null, user.facebookId); }); passport.deserializeUser(function(id, done) { routes.findUserById(id, function(err, user) { done(err, user); }); }); passport.use(new FacebookStrategy({ clientID: FACEBOOK_APP_ID, clientSecret: FACEBOOK_APP_SECRET, callbackURL: FACEBOOK_CALLBACK_URL, profileFields: ['id', 'displayName', 'link', 'about_me', 'photos', 'email'] }, routes.handleLogin ));
使用护照初始化和会话
app.use(passport.initialize()); app.use(passport.session());
实际的请求处理,请注意我正在使用正确的范围
app.get('/auth/facebook', passport.authenticate('facebook', { scope: ['user_about_me', 'email'] })); app.get('/auth/facebook/callback', passport.authenticate('facebook', { successRedirect: '/', failureRedirect: '/error' }));
这是我在路由器中的用户创buildfunction
exports.handleLogin = function(accessToken, refreshToken, profile, done) { db.userCatalog.findOne({ facebookId: profile.id }, function(err, existingUser) { if (err) { return done(err); } else { if(existingUser) { console.log('User: ' + existingUser.name + ' found and logged in!'); done(null, existingUser); } else { new db.userCatalog({ name: profile.displayName, facebookId: profile.id, link: profile.link, picture: profile.photos[0].value, bio: profile.about_me, email: profile.email }).save(function (err, data) { if (err) { return done(err); } else { console.log('New user: ' + data + ' created and logged in!'); done(null, data); } }); } } }); };
以及完成login程序后创build新用户的结果:
我相信这是一些菜鸟的错误,但我自己弄不明白。
Facebook返回一些默认属性。 如果你想访问关于客户端configuration文件的更多细节,你必须在FacebookStrategy
下声明:
passport.use(new FacebookStrategy({ clientID: "...", clientSecret: "...", callbackURL: "...", profileFields: ['id', '...', '...', 'photos', 'emails'] }, ...
所以一旦你声明了你希望从Facebook接收到的属性,当有人试图login你的系统时,他会被要求与你/你的应用程序分享他的照片或电子邮件。 一旦他批准这个,你可以访问它的值:
profile.photos[0].value, profile.emails[0].value, ...
对于电子邮件,有时需要更改:
passport.authenticate('facebook');
对此:
passport.authenticate('facebook', { scope: 'email'}));
在profileFields你使用电子邮件(plular),而不是电子邮件(单数):
profileFields: ['id', 'displayName', 'link', 'about_me', 'photos', 'emails']
这是在Facebook的护照文件README.md :
profileFields参数,指定一个字段列表(以便携式联系人约定命名)
你可以在这里find便携式的通讯协议passportjs