簡體   English   中英

如何使用omniauth google oauth2獲取rails app的'refresh_token'?

[英]How do I get back a 'refresh_token' for rails app with omniauth google oauth2?

幾個月前,我創建了一個使用oauth2進行身份驗證的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

我的initializers / omniauth.rb文件中是否可能缺少某些內容? 我已經嘗試將以下內容添加到選項哈希中,但這似乎沒有帶回刷新令牌:

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

任何幫助將不勝感激! 提前致謝!

提示:'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

正如我所看到的,添加就足夠了

access_type: 'offline'

到您的提供商的范圍。

Google定義中的訣竅如下:刷新令牌僅在您的應用首次訪問Google帳戶時提供。

如果您想要再次查看Google發送的刷新令牌,請拒絕授權並重新獲得授權。

請在此處查看google原始定義:“如果您的應用程序需要在瀏覽器中沒有用戶時刷新訪問令牌,請使用access_type:offline 。這將導致您的應用程序在您的應用程序第一次交換授權代碼獲取刷新令牌對於用戶。“ https://developers.google.com/identity/protocols/OAuth2WebServer

您的范圍看起來需要userinfo.emailuserinfo.profile

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM