Rails Omniauth Facebook无法返回默认字段外的信息字段求助
解决Rails 5中Devise OmniAuth Facebook无法获取指定用户字段的问题
我帮你梳理几个关键排查点和解决步骤,应该能搞定这个问题:
1. 补充缺失的权限Scope
你当前配置里的scope只设置了email,但name、first_name、last_name、gender这些字段属于Facebook的public_profile权限范围,必须在scope中声明才能获取到。
把scope修改为包含public_profile:
config.omniauth :facebook, "APP ID", "APP Secret", scope: 'email,public_profile', secure_image_url: true, image_size: 'large', auth_type: 'https', info_fields: 'email,name,first_name,last_name,gender', client_options: { site: "https://graph.facebook.com/v3.0", authorize_url: "https://www.facebook.com/v3.0/dialog/oauth" }
2. 确保回调逻辑正确提取字段
即使Facebook返回了这些字段,你还需要在OmniAuth回调控制器和User模型里正确读取并保存它们。
比如在你的OmniauthCallbacksController的facebook方法中:
def facebook @user = User.from_omniauth(request.env["omniauth.auth"]) if @user.persisted? sign_in_and_redirect @user, event: :authentication set_flash_message(:notice, :success, kind: "Facebook") if is_navigational_format? else session["devise.facebook_data"] = request.env["omniauth.auth"].except(:extra) redirect_to new_user_registration_url end end
然后在User模型的from_omniauth方法里,要明确处理这些字段:
def self.from_omniauth(auth) where(provider: auth.provider, uid: auth.uid).first_or_create do |user| user.email = auth.info.email user.name = auth.info.name user.first_name = auth.info.first_name user.last_name = auth.info.last_name user.gender = auth.info.gender # 生成随机密码,因为Devise需要密码字段 user.password = Devise.friendly_token[0, 20] end end
3. 重新授权测试
注意:之前已经授权过的用户,Facebook不会重新请求权限,所以你需要退出当前的Facebook账号,然后重新走一遍授权流程,这样新的scope才会生效,Facebook才会返回你需要的字段。
4. (可选)升级Graph API版本
你当前使用的是v3.0版本,这个版本比较老旧了,Facebook后续可能会逐步停止支持。建议升级到较新的稳定版本(比如v18.0),只需要修改client_options里的版本号即可:
client_options: { site: "https://graph.facebook.com/v18.0", authorize_url: "https://www.facebook.com/v18.0/dialog/oauth" }
按照上面的步骤调整后,应该就能获取到你指定的所有用户字段了。
内容的提问来源于stack exchange,提问作者manohar vadapalli
相关产品推荐
相关产品推荐

