2013-05-30 2 views
4

Я так смущен OAuth и Google. Мне потребовалось много времени, чтобы получить refresh_token для создания нового access_token. Тогда узнать, что refresh_token истекает тоже? В чем смысл этого !!! ??Точки доступа Google OAuth

Все, что мне нужно сделать, это сохранить действительный access_token для использования с legato.

Вот что я вручную ввести в свой терминал, чтобы получить код OAuth:

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 как к переменной окр и получить маркер доступа:

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

Тогда я могу получить доступ к access_token и 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 

Через час, мои жетоны истекает, и у меня есть вручную запустить процесс снова из браузера! Как я могу воспроизвести это в коде?

+0

Я не думаю, что вы нашли ответ еще. Я сталкиваюсь с той же проблемой. – juanpaco

+0

Нет, у меня нет, но я считаю, что решение включает использование обратного вызова. Я открыл здесь более конкретный вопрос: http://stackoverflow.com/questions/16864199/how-to-configure-route-for-oauth-callback/16923267?noredirect=1#16923267. У меня еще не было возможности опробовать представленный ответ. – mnort9

ответ

3

Здесь вы идете, сделал кое-что только для вас :)

Это простая реализация, в частности, чтобы облегчить боль обновляя лексемы.

Просто убедитесь, что:

  1. положить в свой собственный APP_ID и APP_SECRET.
  2. Либо только сохранить refresh_token и вызывать refresh_token() каждый раз, прежде чем использовать его, или использовать refresh_token_if_needed() каждый раз, и повторно сохранить token и expires_at (предпочтительный, очевидно, так как вы будете обновлять только в случае необходимости).
  3. Дайте мне знать, как это работает.

.

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 
+0

Спасибо. Я взял ваш код и сделал отличный класс: https://gist.github.com/Overbryd/0ae6287b02a9848e5b67 – Overbryd

+0

Прохладный, рад слышать – Wiz

 Смежные вопросы

  • Нет связанных вопросов^_^