Google OAuth 访问令牌 [英] Google OAuth access tokens

查看:106
本文介绍了Google OAuth 访问令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 OAuth 和 Google 感到很困惑.我花了很长时间才获得 refresh_token 以创建新的 access_token.然后找出refresh_token也过期了??这有什么意义!!!?

I'm so confused by OAuth and Google. It took me forever to get the refresh_token to create a new access_token. Then to find out the refresh_token expires too?? What is the point of that!!!??

我需要做的就是保留一个有效的 access_token 以用于 legato.

All I need to do is persist a valid access_token for use with legato.

这是我手动输入终端以检索 OAUTH 代码的内容:

Here is what I manually enter into my terminal to retrieve an OAUTH code:

client = OAuth2::Client.new('GA_CLIENT_ID', 'GA_SECRET_KEY', {
        :authorize_url => 'https://accounts.google.com/o/oauth2/auth',
        :token_url => 'https://accounts.google.com/o/oauth2/token'
})
client.auth_code.authorize_url({
       :scope => 'https://www.googleapis.com/auth/analytics.readonly',
       :redirect_uri => 'http://localhost',
       :access_type => 'offline',
       :approval_prompt=> 'force'
}) 

然后我在浏览器中手动输入输出的 url.我将返回的 OAUTH 代码导出为一个 env 变量并获取访问令牌:

Then I manually enter the outputted url to in my browser. I export the returned OAUTH code as to an env variable and get the access token:

access_token = client.auth_code.get_token(ENV['GA_OAUTH_CODE'], :redirect_uri => 'http://localhost')

然后我就可以访问access_token和refresh_token了:

Then I can access the access_token and refresh_token:

   begin
      api_client_obj = OAuth2::Client.new(ENV['GA_CLIENT_ID'], ENV['GA_SECRET_KEY'], {:site => 'https://www.googleapis.com'})
      api_access_token_obj = OAuth2::AccessToken.new(api_client_obj, ENV['GA_OAUTH_ACCESS_TOKEN'])
      self.user = Legato::User.new(api_access_token_obj)
      self.user.web_properties.first # this tests the access code and throws an exception if invalid
    rescue Exception => e
      refresh_token
    end

  end

  def refresh_token
    refresh_client_obj =  OAuth2::Client.new(ENV['GA_CLIENT_ID'], ENV['GA_SECRET_KEY'], {
            :authorize_url => 'https://accounts.google.com/o/oauth2/auth',
            :token_url => 'https://accounts.google.com/o/oauth2/token'
        })
    refresh_access_token_obj = OAuth2::AccessToken.new(refresh_client_obj, ENV['GA_OAUTH_ACCESS_TOKEN'], {refresh_token: ENV['GA_OAUTH_REFRESH_TOKEN']})
    refresh_access_token_obj.refresh!
    self.user = Legato::User.new(refresh_access_token_obj)
  end

一小时后,我的令牌过期,我必须从浏览器重新手动启动该过程!我如何在代码中复制这个?

After an hour, my tokens expire and I have to manually start the process over again from the browser! How can I replicate this in code??

推荐答案

给你,为你做了一些小事 :)

Here you go, made a little something just for you :)

这是一个简单的实现,专门用于减轻更新令牌的痛苦.

It's a simple implementation, specifically to ease the pain of renewing tokens.

请务必:

  1. 输入您自己的APP_IDAPP_SECRET.
  2. 要么只保存您的refresh_token 并在每次使用前调用refresh_token(),或者每次都使用refresh_token_if_needed(),并且重新保存 tokenexpires_at(显然是首选,因为您只会在需要时刷新).
  3. 告诉我结果如何.
  1. Put in your own APP_ID and APP_SECRET.
  2. Either only save your refresh_token and call refresh_token() every time before you use it, or use refresh_token_if_needed() every time, and re-save the token and expires_at (preferred obviously , since you'll only refresh when needed).
  3. Let me know how it worked out.

.

require 'gmail'
require 'gmail_xoauth'
require 'httparty'

class GmailManager
  APP_ID      = "DDDDDDDDDDDD-SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS.apps.googleusercontent.com"
  APP_SECRET  = "SSSSSS-SSSSSSSSSSSSSSSSS"

  def refresh_token(refresh_token)
    Rails.logger.info "[GmailManager:refresh_token] refreshing using this refresh_token: #{refresh_token}"
    # Refresh auth token from google_oauth2 and then requeue the job.
    options = {
      body: {
        client_id:     APP_ID,
        client_secret: APP_SECRET,
        refresh_token: refresh_token,
        grant_type:    'refresh_token'
      },
      headers: {
        'Content-Type' => 'application/x-www-form-urlencoded'
      }
    }
    response = HTTParty.post('https://accounts.google.com/o/oauth2/token', options)
    if response.code == 200
      token = response.parsed_response['access_token']
      expires_in = DateTime.now + response.parsed_response['expires_in'].seconds
      Rails.logger.info "Success! token: #{token}, expires_in #{expires_in}"
      return token, expires_in
    else
      Rails.logger.error "Unable to refresh google_oauth2 authentication token."
      Rails.logger.error "Refresh token response body: #{response.body}"
    end
    return nil, nil
  end

  def refresh_token_if_needed(token, expires_on, refresh_token)
    if token.nil? or expires_on.nil? or Time.now >= expires_on
      Rails.logger.info "[GmailManager:refresh_token_if_needed] refreshing using this refresh_token: #{refresh_token}"
      new_token, new_expires_on = self.refresh_token(refresh_token)
      if !new_token.nil? and !new_expires_on.nil?
        return new_token, new_expires_on
      end
    else
      Rails.logger.info "[GmailManager:refresh_token_if_needed] not refreshing. using this token: #{token}"
    end
    return token, expires_on
  end
end

这篇关于Google OAuth 访问令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆