【问题标题】:rails API error: Validation failed: Email is invalidrails API 错误:验证失败:电子邮件无效
【发布时间】:2021-12-27 11:03:44
【问题描述】:

我希望你很好。我尝试对我的 Rails API 实施谷歌身份验证。我得到错误

ActiveRecord::RecordInvalid (Validation failed: Email is invalid)

我的用户.rb:

    class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable,
         :confirmable, :trackable,
         :omniauthable, omniauth_providers: [:google_oauth2]

  def self.create_user_for_google(data)
    where(uid: data['email']).first_or_initialize.tap do |user|
      user.provider = 'google_oauth2'
      user.uid = data['email']
      user.email = data['email']
      user.password = Devise.friendly_token[0, 20]
      user.password_confirmation = user.password
      user.save!
    end
  end
end

我的 users_controller.rb 看起来:

    class UsersController < ApplicationController
  def google_oauth2
    url = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=#{params['id_token']}"
    response = HTTParty.get(url, format: :plain)
    
    user = User.create_user_for_google(response.parsed_response)
    
    render json: user
  end
end

【问题讨论】:

  • 你能分享HTTParty.get(url, format: :plain)的回复吗?

标签: ruby-on-rails ruby authentication


【解决方案1】:

我猜response.parsed_response 中没有email

您不应该以您的方式从后端发出请求:

HTTParty.get "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=#{params['id_token']}"

您应该将用户的浏览器重定向到 user_google_oauth2_omniauth_authorize_url(我认为这个 URL 助手来自 routes.rb 中的设计(查找 devise_for:

然后您的用户的浏览器显示谷歌登录页面(或者,如果用户已经登录,下一步)然后(仍然是谷歌)请求他们同意共享数据,只有在收到此同意后谷歌才会重定向您的用户回到你的应用到一个叫做回调的地址(看起来像omniauth_callbacks: "users/omniauth_callbacks"

并且只有在处理此回调的控制器/操作中,您才会看到一封电子邮件和一个令牌,您可以与您的用户一起保存并使用它来使用 google 的 oAuth 协议登录。

别担心,第一次使用 oAuth 时会感到困惑。

我能找到的关于如何实现全方位身份验证的最清晰的分步示例之一是:https://www.digitalocean.com/community/tutorials/how-to-configure-devise-and-omniauth-for-your-rails-application

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-17
    • 2015-11-09
    相关资源
    最近更新 更多