使用omniauth-google-oauth2 gem从auth哈希中检索first_name和last_name

时间:2016-08-02 17:15:40

标签: ruby-on-rails devise omniauth

我使用omniauth-google-oauth2 gem设置了rails 4.2.7 app设置,我想从auth哈希中检索first_namelast_name

通过将omniauth-facebook修改为如下所示,我可以使用devise.rb gem执行此操作,

devise.rb

# Omniauth / Oauth2 settings
  callback_url = if Rails.env == "development"
   ENV['FB_CALLBACK']
  else
    ENV['FB_CALLBACK_PROD']
  end

  config.omniauth :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET'], callback_url: callback_url,
   :scope => 'email',
   :info_fields => 'email, first_name, last_name'
  # Google - OmniAuth
  require 'omniauth-google-oauth2'
  config.omniauth :google_oauth2, ENV["GOOGLE_CLIENT_ID"], ENV["GOOGLE_CLIENT_SECRET"]

但是,我似乎无法弄清楚如何使用omniauth-google-oauth2检索first_name / last_name。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

来自omniauth-google-oauth2的@chris,在你的回调控制器动作中,

auth = request.env['omniauth.auth']

request.env['omniauth.auth']将包含用户身份验证会话的哈希值,infoauth["info"]

保留基本用户信息
auth
====
{
.....
"info"=>
  {"name"=>"Username",
   "email"=>"Useremail",
   "first_name"=>"firstname",
   "last_name"=>"lastname",
   "image"=> "image_url",
   "urls"=>{"Google"=>"https://plus.google.com/xxxxxxxxxxxxxxxxx"}
  }
....
}