我正在尝试使用 passport-facebook 为我的应用程序建立登录系统。 一切顺利,除了从请求中返回未定义的 2 个字段。
我将发布我的整个登录过程代码,因为我在这里没有看到很多关于它的信息,即使有很多问题。
这是app.js中的配置
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
));
使用 Passport 初始化和 session
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' }));
这是我在路由器中的用户创建功能
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);
}
});
}
}
});
};
我确定这是一些菜鸟的错误,但我自己无法弄清楚......
最佳答案
Facebook 返回一些默认属性。如果您想访问有关客户资料的更多详细信息,您必须在 FacebookStrategy
下声明它:
passport.use(new FacebookStrategy({
clientID: "...",
clientSecret: "...",
callbackURL: "...",
profileFields: ['id', '...', '...', 'photos', 'emails']
}, ...
因此,一旦您声明了希望从 Facebook 接收的属性,当有人尝试登录您的系统时,系统会要求他与您/您的应用分享他的照片或电子邮件。一旦他批准了,您就可以访问它的值:
profile.photos[0].value,
profile.emails[0].value,
...
对于电子邮件,有时更改是有用的:
passport.authenticate('facebook');
到这里:
passport.authenticate('facebook', { scope: 'email'}));
关于node.js - passport-facebook - 无法获取 about_me 和电子邮件个人资料字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20291357/