【问题标题】:"Missing authorization code" error when trying to use Google Calendar API尝试使用 Google Calendar API 时出现“缺少授权代码”错误
【发布时间】:2012-06-24 09:31:00
【问题描述】:

以下是我用来让用户允许用户授权我的应用通过 OAuth 访问他们的 Google 日历的代码。我基于this sample code

它在大多数情况下都有效,但有时,services 控制器的 create_google_calendar 操作中的 client.authorization.fetch_access_token! 行出现 ArgumentError: Missing authorization code 错误。如果我注释掉该行,所有client.authorization 属性都是null

我正在使用 Rails 3.2.0 和 Ruby 1.9.2。

这是什么原因造成的?

宝石文件

gem 'google-api-client', :require => 'google/api_client'

服务.rb

def self.google_calendar_client google_calendar_service=nil
    client = Google::APIClient.new
    client.authorization.client_id = xxx
    client.authorization.client_secret = xxx
    client.authorization.scope = 'https://www.googleapis.com/auth/calendar'
    url_prefix = Rails.env.production? ? xxx : 'http://localhost:3000'
    client.authorization.redirect_uri = "#{url_prefix}/create_google_calendar"
    if google_calendar_service.present?
        client.authorization.update_token! :access_token => google_calendar_service.token, :refresh_token => google_calendar_service.google_calendar_refresh_token, :expires_in => google_calendar_service.google_calendar_expires_in, :issued_at => Time.at(google_calendar_service.google_calendar_issued_at)
        client.authorization.fetch_access_token! if client.authorization.expired?
    end

    client
end

services_controller.rb

def connect_google_calendar
    @google_calendar_url = Service.google_calendar_client.authorization.authorization_uri.to_s
end

def create_google_calendar
    client = Service.google_calendar_client
    client.authorization.code = params[:code]
    client.authorization.fetch_access_token!
    current_user.services.create :provider => 'google_calendar', :token => client.authorization.access_token, :google_calendar_refresh_token => client.authorization.refresh_token, :google_calendar_expires_in => client.authorization.expires_in, :google_calendar_issued_at => client.authorization.issued_at
end

【问题讨论】:

    标签: ruby-on-rails google-api oauth-2.0 google-api-client


    【解决方案1】:

    事实是,我不知道。你的代码对我来说很合适。但我至少可以告诉你错误的含义。缺少授权码意味着它认为您在获取访问令牌时正在尝试执行“授权码”授权类型。如果您实际上是在尝试从刷新令牌中获取访问令牌,而不是在获得用户授权后的第一次通过时,那么您可能没有正确设置授权对象。

    您可以通过检查 client.authorization.grant_type 值来检查这一点。在客户端的最新版本中,您可以手动设置 grant_type 值以强制使用特定模式,这可能会为您提供更多信息性错误消息,具体取决于实际问题。

    【讨论】:

      猜你喜欢
      • 2013-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-20
      • 2016-12-11
      • 2016-11-20
      相关资源
      最近更新 更多