Skip to content

Instantly share code, notes, and snippets.

@marshluca
Created December 10, 2010 08:52
Show Gist options
  • Save marshluca/735986 to your computer and use it in GitHub Desktop.
Save marshluca/735986 to your computer and use it in GitHub Desktop.
新浪微薄的OAuth 1.0认证
# OAuth认证包括以下四步内容
# 1. 获取Request Token
# 2. 用户确认授权
# 3. 换取Access Token
# 4. 访问受限资源
require 'rubygems'
gem 'oauth','0.4.3'
require 'oauth'
API_KEY = "1860579545"
API_KEY_SECRET = "d62c11d9ddaa25d55fc59b1835e73619"
SITE = "http://api.t.sina.com.cn"
# 1. 获取Request Token
@consumer=OAuth::Consumer.new(API_KEY, API_KEY_SECRET, { :site => SITE })
@[email protected]_request_token
puts @request_token.inspect
# 2. 用户确认授权
callback_url = "http://localhost.com/oauth"
url = "#{@request_token.authorize_url}&oauth_token_secret=#{@request_token.secret}&oauth_callback=#{callback_url}"
puts "请将下面url粘贴到浏览器中,并同意授权,同意后按任意键继续:\n#{url}"
# response = Net::HTTP.get(URI.parse(url))
# puts response.body
# here wating 20 seconds to save oauth_verfier to verifier.txt manually
sleep(20)
# 3. 通过授权码oauth_verfier换取access_token
oauth_verifier = IO.readlines("verifier.txt").first.strip
verify_hash = {:oauth_verifier=> oauth_verifier}
@access_token=@request_token.get_access_token(verify_hash)
# i should re-generate access_token proxy here,
# since ruby oauth library assume the domain of the auth site should be same with the resource site
# @access_token = OAuth::AccessToken.new(@consumer, @access_token.token, @access_token.secret)
# puts @access_token.inspect
# 4. 通过access_token访问受限资源(API)
@response = @access_token.get "/statuses/home_timeline.xml"
puts @response.body
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment