【问题标题】:Offline access to google contacts using the oauth2 ruby gem使用 oauth2 ruby​​ gem 离线访问谷歌联系人
【发布时间】:2015-06-19 15:26:57
【问题描述】:

我正在尝试使用 oauth2 ruby​​ Gem (https://github.com/intridea/oauth2) 离线访问 Google 联系人。我当前的代码是:

#!/usr/bin/env ruby

require 'oauth2'
require 'yaml'
require 'pp'

auth = YAML.load_file('.auth.yml')
client_id = auth['google']['clientid']
client_secret = auth['google']['secret']
redirect = 'urn:ietf:wg:oauth:2.0:oob'
code = ARGV[0]
token = nil

client = OAuth2::Client.new(client_id, client_secret, site: 'https://accounts.google.com', token_url: '/o/oauth2/token', authorize_url: '/o/oauth2/auth')
if code
  token = client.auth_code.get_token(code, :redirect_uri => redirect)
  auth['google']['token'] = token.to_hash
  open('.auth.yml', 'w'){|f| f.write(auth.to_yaml)}
elsif auth['google']['token']
  token = OAuth2::AccessToken.from_hash(client, auth['google']['token'])
  token.refresh! if token.expired?
  auth['google']['token'] = token.to_hash
  open('.auth.yml', 'w'){|f| f.write(auth.to_yaml)}
else
  puts client.auth_code.authorize_url(scope: 'https://www.google.com/m8/feeds', redirect_uri: redirect, access_type: :offline)
end

pp token.expired? if token

我可以使用它来获取一个访问令牌,有效期为一小时,当我提交从生成的 URL 的确认屏幕获得的代码时,我确实在收到的响应中看到了一个 refresh_token,但只有确认屏幕提示我访问我的联系人,它不会询问我是否要离线访问,并且令牌确实会在一小时后过期。我做错了什么?

【问题讨论】:

    标签: ruby oauth-2.0 google-contacts-api


    【解决方案1】:

    每个访问令牌都会在一小时后过期。当您不请求离线时,用户必须再次授予访问权限才能获得新的访问令牌。

    如您所述,在请求离线访问令牌时,您将收到一个刷新令牌。您将使用此刷新令牌在过期之后或之前请求新的访问令牌。这样做是为了让用户不会每小时都被打扰来授予访问权限。

    这里是关于刷新令牌的文档:https://developers.google.com/identity/protocols/OAuth2WebServer#refresh

    【讨论】:

    • 但这就是上面代码的作用,对吧?我得到了刷新令牌(我可以在保存它的 yaml 文件中看到它)并且刷新它时没有错误,但是一个小时后,最后一行开始打印'false'
    • 我查看了其他请求离线访问的应用程序,例如完全联系。如果我访问他们的身份验证 URL (is.gd/nZOohu),系统会提示我进行离线访问;如果我用我自己的重定向 uri 和客户端 ID 替换,我不是。看起来这是我在 api 控制台中的 APP 设置中的东西,但如果我知道的话,该死的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-01
    • 1970-01-01
    • 2014-05-22
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多