在过去的几天里,我一直在努力支持在我的 Rails 3 应用程序中向 Google Contacts API 添加联系人的能力。尽管有许多错误的开始,但我终于通过使用 Ruby OAuth gem 并按照此处的教程取得了一些进展:http: //everburning.com/news/google-analytics-oauth-and-ruby-oh-my/
当我在控制台中执行此操作时,我比在我的 Rails 应用程序中走得更远。我可以创建访问令牌,使用联系人 API 的特定范围对 Google 服务进行身份验证,并应用 oauth_verifier 令牌来获取访问令牌。但是当需要推送数据时,我收到了这个错误:
response = at.post("https://www.google.com/m8/feeds/contacts/default/full", gdata)
=> #<Net::HTTPUnauthorized 401 Unknown authorization header readbody=true>
“readbody=true”标头来自哪里,我将如何摆脱它?
但在 Rails 应用程序中情况更糟。我有一个控制器操作(“googlecontacts”)创建请求令牌并将用户引导到使用 Google 的身份验证站点:
def googlecontacts
@card = Card.find_by_short_link(params[:id])
@consumer = OAuth::Consumer.new(
'anonymous',
'anonymous',
{
:site => 'https://www.google.com',
:request_token_path => '/accounts/OAuthGetRequestToken',
:access_token_path => '/accounts/OAuthGetAccessToken',
:authorize_path => '/accounts/OAuthAuthorizeToken',
:signature_method => 'HMAC-SHA1',
:oauth_version => '1.0'
})
@request_token = @consumer.get_request_token(
{:oauth_callback => 'http://monkey.dev/cards/google_auth?redir='+@card.short_link},
{:scope => "https://www.google.com/m8/feeds/"}
)
session[:request_token] = @request_token
redirect_to @request_token.authorize_url
end
这似乎有效;我得到一个工作请求令牌对象,用户被转发到 Google 服务进行身份验证。回调 URL(“google_auth”)应采用 oauth_verifier 令牌来创建访问令牌。这是控制器的开头:
def google_auth
@access_token = session[:request_token].get_access_token(:oauth_verifier=>params[:oauth_verifier])
这就是它失败的地方。最后一行的错误是:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]
但是其中的值—— session[:request_token] 和 params[:oauth_verifier]—— 存在并在该操作中说明!我无法弄清楚这里的 nil 是什么。
所以我想我需要先弄清楚第二个问题,但回答第一个问题也可以加分。:-)
谢谢阅读。
亚伦。