Twitter应用程序仅Auth

我正在尝试按照此链接的步骤获取Application Only Auth令牌: https : //dev.twitter.com/docs/auth/application-only-auth

我正在使用Ruby on Rails和Rest Client来提供所需的POST请求,我正在设置标题(我认为)。

一步一步说:

URL根据RFC 1738编码使用者密钥和使用者密钥。请注意,在编写本文时,这实际上不会更改使用者密钥和密钥,但是如果这些值的格式发生变化,仍应执行此步骤。未来。

将编码的使用者密钥,冒号字符“:”和编码的使用者密钥连接成单个字符串。

Base64对上一步中的字符串进行编码。

我的代码是:

require 'rest_client' key = URI::encode('app_key') secret = URI::encode('app_secret') encoded = Base64.encode64("#{key}:#{secret}") res = RestClient::Resource.new "https://api.twitter.com/oauth2/token/" response = '' options = {} options['Authorization'] = "Basic #{encoded}" options['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8' res.post('grant_type=client_credentials', options) do |response, request, result| response << "#{CGI::escapeHTML(response.inspect)}

" response << "#{CGI::escapeHTML(request.inspect)}

" response << "#{CGI::escapeHTML(result.inspect)}
" end render :text => txt

我打印出这个:

 "{\"errors\":[{\"label\":\"authenticity_token_error\",\"code\":99,\"message\":\"Unable to verify your credentials\"}]}" #"Basic bXlfa2V5Om15X3NlY3JldA==\n", "Content-Type"=>"application/x-www-form-urlencoded;charset=UTF-8"}, @url="https://api.twitter.com/oauth2/token/", @cookies={}, @payload="", @user=nil, @password=nil, @timeout=nil, @open_timeout=nil, @block_response=nil, @raw_response=false, @verify_ssl=false, @ssl_client_cert=nil, @ssl_client_key=nil, @ssl_ca_file=nil, @tf=nil, @max_redirects=10, @processed_headers={"Accept"=>"*/*; q=0.5, application/xml", "Accept-Encoding"=>"gzip, deflate", "Authorization"=>"Basic bXlfa2V5Om15X3NlY3JldA==\n", "Content-Type"=>"application/x-www-form-urlencoded;charset=UTF-8", "Content-Length"=>"29"}, @args={:method=>:post, :url=>"https://api.twitter.com/oauth2/token/", :payload=>"grant_type=client_credentials", :headers=>{"Authorization"=>"Basic bXlfa2V5Om15X3NlY3JldA==\n", "Content-Type"=>"application/x-www-form-urlencoded;charset=UTF-8"}}> # 

我的钥匙和秘密是有效的。 我错过了什么吗?

谢谢!


编辑:

使用我发现的解决方案进行更新。

问题出在Base64转换和字符串编码上。

我必须为密钥+秘密组合添加强制编码参数,用于UTF-8转换:

 encoded = Base64.encode64("#{key}:#{secret}".force_encoding('UTF-8')) 

Rails Base64.encode64每60个编码字符插入一个换行符。

解决方法是:

对于Ruby 1.9+(strict_包含在Ruby 1.9中)

 Base64.strict_encode64(string) 

对于Ruby 1.9-

 Base64.encode64(string).gsub('/\n/') # To remove the line break 

您是否尝试使用Tweeter(作为OAuth提供程序)实施授权。 我建议使用OmniAuth,而不是在API文档之后从头开始编写它。 设置和样板代码相当容易使用。

有关它的更多信息,请访问http://www.omniauth.org/&https://github.com/intridea/omniauth/wiki

如果这有助于您,请告诉我们。