【问题标题】:Google Authentication error Ruby on RailsGoogle 身份验证错误 Ruby on Rails
【发布时间】:2018-04-27 04:43:14
【问题描述】:

我正在尝试在我的 Rails 应用程序上实施 Google 身份验证,但遇到了一些问题。

https://richonrails.com/articles/google-authentication-in-ruby-on-rails/ 之后,我使用从 Google 开发者控制台“omniauth.rb”获得的密钥创建了我的初始化程序

OmniAuth.config.logger = Rails.logger

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :google_oauth2, '*****', '*****', {client_options: {ssl: {ca_file: Rails.root.join("cacert.pem").to_s}}}
end

我添加了一些路线

  # GOOGLE AUTH
  get 'auth/:provider/callback', to: 'sessions#create'
  get 'auth/failure', to: redirect('/')
  get 'signout', to: 'sessions#destroy', as: 'signout'

我的会话的创建操作

def create
    user = User.from_omniauth(env["omniauth.auth"])
    sign_in user
    flash[:success] = 'Logged in!'
    redirect_to root_path
end

以及用户模型中的User.from_omniauth方法

def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user|
      user.password = user.password_confirmation = user.password_digest =  SecureRandom.urlsafe_base64(n=6)
      user.provider = auth.provider
      user.uid = auth.uid
      user.name = auth.info.name
      user.oauth_token = auth.credentials.token
      user.oauth_expires_at = Time.at(auth.credentials.expires_at)
      user.save!
    end
  end

我设置了一个随机密码,因为我也在使用 bcrypt 身份验证,它强制每个用户都有一个密码

最后,在我看来,我有一个登录按钮

= link_to "Sign in with Google", "/auth/google_oauth2", id: "sign_in", class: "btn btn-primary"

问题是它不起作用,当我单击它时,会话的创建user = User.from_omniauth(env["omniauth.auth"]) 上显示错误:

NameError at /auth/google_oauth2/callback
undefined local variable or method `env' for #<SessionsController:0x956eb90>

其他时候它会在另一行抛出SSL_connect SYSCALL returned=5 errno=0 state=SSLv2/v3 read server hello A (OpenSSL::SSL::SSLError),但我想这是一个不同的错误。

【问题讨论】:

  • 你试过用ENV代替吗?

标签: ruby-on-rails ruby authentication google-authentication


【解决方案1】:

没有可用的env 方法。 而不是这个,使用

user = User.from_omniauth(request.env["omniauth.auth"])

在您的创建方法中,request.env["omniauth.auth"] 对象具有在用户向您的应用程序身份验证后由谷歌发送的信息。

【讨论】:

    猜你喜欢
    • 2018-03-02
    • 2015-08-08
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多