【问题标题】:How do I get back a 'refresh_token' for rails app with omniauth google oauth2?如何使用omniauth google oauth2取回rails应用程序的“refresh_token”?
【发布时间】:2013-07-27 11:33:07
【问题描述】:

几个月前,我创建了一个使用 oauth2 通过 google 进行身份验证的 rails 应用程序 - 具体来说,omniauth-google-oauth2 gem。我已经完成了创建身份验证和存储刷新令牌的所有步骤,但最近 oauth2 停止将“refresh_token”作为响应的一部分发回。最初我收到的回复包含:

credentials: {
  refresh_token: XXX,
  token: YYY,
  expires_at: 1374840767,
  expires: true
},

现在我只取回一个小时内过期的令牌:

credentials: {
  token: YYY,
  expires_at: 1374840767,
  expires: true
},

我真的不知道我在应用程序方面做了什么来改变这一点,所以我不确定谷歌是否改变了一些东西,或者它是否是我所做的。对于上下文,我的代码如下所示:

初始化程序/omniauth.rb:

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :google_oauth2, 'KEY', 'SECRET', {:scope => "userinfo.email,userinfo.profile,analytics.readonly,adsense.readonly"}
end

authentications_controller.rb 是我收到响应的地方:

def create
  auth = request.env["omniauth.auth"] 
  params = request.env["omniauth.params"]
  project = Project.find(params['project_id'])

  Authentication.create(:project_id => project.id, :provider => auth['provider'], :uid => auth['uid'], :access_token => auth['credentials']['refresh_token'])
  flash[:notice] = "Authentication successful."
  redirect_to owner_view_project_path(project)
end

我的初始化程序/omniauth.rb 文件中是否可能缺少某些内容?我尝试将以下内容添加到选项哈希中,但这似乎并没有带回刷新令牌:

:approval_prompt => "force", :access_type => "offline"

任何帮助将不胜感激!提前致谢!

【问题讨论】:

  • 这个问题你解决了吗?我/我现在面临同样的问题,我很乐意看到你的解决方案。谢谢!

标签: ruby-on-rails oauth-2.0 omniauth


【解决方案1】:

如我所见,添加就足够了

access_type: 'offline'

到您的提供商的范围。

在 Google 定义中的诀窍如下:刷新令牌仅在您的应用第一次访问 google 帐户时提供

如果您想再次查看 google 发送的刷新令牌,请拒绝授权并重新获得授权。

在此处查看谷歌原始定义:“如果您的应用程序需要在用户不在浏览器时刷新访问令牌,则使用 access_type:offline。这将导致您的应用程序获得刷新令牌第一次您的应用程序为用户交换授权码。” (https://developers.google.com/identity/protocols/OAuth2WebServer)

【讨论】:

    【解决方案2】:

    prompt: 'consent' 正在为您提供刷新令牌。像这样的东西应该可以工作:

    Rails.application.config.middleware.use OmniAuth::Builder do
      scopes = [
          # we need the profile scope in order to login
          "https://www.googleapis.com/auth/userinfo.profile",
          # this and other scopes could be added, but match them up with the
          # features you requested in your API Console
          "https://www.googleapis.com/auth/calendar"
        ]
    
      provider :google_oauth2, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, { scope: scopes.join(" "), access_type: 'offline',  prompt: 'consent'}
    end
    

    【讨论】:

    • 提示:“同意”为我做了
    • 感谢提示:“同意”救了我
    • 背景:看起来refresh_token 仅在用户明确确认访问时才包含(这总是在第一次请求时发生)。后续授权请求会自动确认,因为 Google 记得该决定,但是,自动确认缺少 refresh_token(这是有道理的)。这个答案告诉如何强制同意,以确保refresh_token 将出现。请注意,这将每次询问用户以确认他的授权。
    【解决方案3】:

    您的范围内似乎需要userinfo.emailuserinfo.profile

    https://github.com/zquestz/omniauth-google-oauth2/issues/27

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-12
      • 2014-03-09
      • 1970-01-01
      • 2012-05-30
      • 1970-01-01
      • 2017-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多