Twitter中的Ruby三脚授权

我在铁轨上尝试我的手ruby。 大部分时间我都在Sinatra编写代码。 无论如何,这个问题可能不需要对框架做任何事情。 这个问题听起来可能是一个非常新手的问题。 我第一次玩Twitter 1.1 API和OAuth。

我创建了一个应用程序XYZ并在Twitter上注册了它。 我得到了XYZ的消费者密钥,即CONSUMER_KEY和消费者秘密,即CONSUMER_SECRET。 我还获得了XYZ自己的访问令牌,即ACCESS_TOKEN和访问机密,即ACCESS_SECRET

XYZ应用程序类型:读取,写入和访问直接消息XYZ回调URL: http ://www.mysite.com/cback我已检查过:允许此应用程序用于通过Twitter登录

我想要做的很简单:

1)用户访问我的网站并点击链接Link your twitter account (不用twitter登录)
2)打开twitter弹出窗口,用户授权XYZ代表他/她执行操作
3)一旦用户允许并弹出窗口关闭,XYZ应用程序将获取用户的访问令牌并保密,并保存在数据库中。
4)然后XYZ使用该用户的令牌和秘密来执行将来的操作。

我可能很蠢,这样的工作流已经在几千个网站上实现,Twitter API文档解释了这个三方认证,但我仍然无法弄明白。

我已阅读https://dev.twitter.com/docs/auth/3-legged-authorization和https://dev.twitter.com/docs/auth/implementing-sign-twitter遗憾的是,互联网上没有找到ruby代码用一步一步的例子解释。

当用户单击Link your twitter account时,应使用什么链接打开Twitter身份validation页面。 任何人都可以在这里用我的pseduo凭证编写一些伪代码来实现我的目标,从这个工作流程结束到最后? 谢谢。

更新:

我开始请求请求令牌为

require 'oauth'
consumer = OAuth::Consumer.new(CONSUMER_KEY, CONSUMER_SECRET,
{ site: "https://twitter.com"})
request_token = consumer.get_request_token oauth_callback: 'http://www.mysite.com/tauth'
redirect_to request_token.authorize_url

我不熟悉ROR,但是当用户点击你的按钮时,你需要遵循OAuth’dance’的工作流程:

  1. 通过发送请求从Twitter获取未经授权的请求令牌

    POST https://api.twitter.com/oauth/request_token

    使用您的消费者秘密签署请求。 这将在后台完成,并对用户透明。

  2. 你将从twitter收到oauth_token和oauth_token_secret。

  3. 将用户重定向到

    https://api.twitter.com/oauth/authorize?oauth_token=%5Btoken_received_from_twitter%5D

    使用您在步骤2中从Twitter收到的oauth令牌值。

  4. 当用户授权您的应用时,他们将被重定向到您的回调url,其中oauth_token和oauth_verifier附加到url。 即

    http://www.mysite.com/cback?oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0&oauth_verifer=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY

  5. 通过将签名请求与oauth_verifier一起发送,将请求令牌转换为访问令牌

    POST https://api.twitter.com/oauth/access_token

    使用您的消费者密钥和在步骤2中收到的令牌秘密签署您的请求。

  6. 如果一切顺利,您将收到来自Twitter的新oauth_tokenoauth_token_secret 。 这是您的用户访问令牌。

  7. 使用在步骤6中收到的访问令牌和秘密,您可以通过向适当的api端点发送签名请求代表用户进行Twitter api呼叫。

希望您此时解决了您的问题,但我构建了此示例使用Twitter ruby​​ Web应用程序登录,该应用程序提供了执行此集成所需的所有说明。 下面是一个用注释实现所有必要方法的类:

 require "net/https" require "simple_oauth" # This class implements the requests that should # be done to Twitter to be able to authenticate # users with Twitter credentials class TwitterSignIn class << self def configure @oauth = YAML.load_file(TWITTER) end # See https://dev.twitter.com/docs/auth/implementing-sign-twitter (Step 1) def request_token # The request to get request tokens should only # use consumer key and consumer secret, no token # is necessary response = TwitterSignIn.request( :post, "https://api.twitter.com/oauth/request_token", {}, @oauth ) obj = {} vars = response.body.split("&").each do |v| obj[v.split("=").first] = v.split("=").last end # oauth_token and oauth_token_secret should # be stored in a database and will be used # to retrieve user access tokens in next requests db = Daybreak::DB.new DATABASE db.lock { db[obj["oauth_token"]] = obj } db.close return obj["oauth_token"] end # See https://dev.twitter.com/docs/auth/implementing-sign-twitter (Step 2) def authenticate_url(query) # The redirection need to be done with oauth_token # obtained in request_token request "https://api.twitter.com/oauth/authenticate?oauth_token=" + query end # See https://dev.twitter.com/docs/auth/implementing-sign-twitter (Step 3) def access_token(oauth_token, oauth_verifier) # To request access token, you need to retrieve # oauth_token and oauth_token_secret stored in # database db = Daybreak::DB.new DATABASE if dbtoken = db[oauth_token] # now the oauth signature variables should be # your app consumer keys and secrets and also # token key and token secret obtained in request_token oauth = @oauth.dup oauth[:token] = oauth_token oauth[:token_secret] = dbtoken["oauth_token_secret"] # oauth_verifier got in callback must # to be passed as body param response = TwitterSignIn.request( :post, "https://api.twitter.com/oauth/access_token", {:oauth_verifier => oauth_verifier}, oauth ) obj = {} vars = response.body.split("&").each do |v| obj[v.split("=").first] = v.split("=").last end # now the we got the access tokens, store it safely # in database, you're going to use it later to # access Twitter API in behalf of logged user dbtoken["access_token"] = obj["oauth_token"] dbtoken["access_token_secret"] = obj["oauth_token_secret"] db.lock { db[oauth_token] = dbtoken } else oauth_token = nil end db.close return oauth_token end # This is a sample Twitter API request to # make usage of user Access Token # See https://dev.twitter.com/docs/api/1.1/get/account/verify_credentials def verify_credentials(oauth_token) db = Daybreak::DB.new DATABASE if dbtoken = db[oauth_token] # see that now we use the app consumer variables # plus user access token variables to sign the request oauth = @oauth.dup oauth[:token] = dbtoken["access_token"] oauth[:token_secret] = dbtoken["access_token_secret"] response = TwitterSignIn.request( :get, "https://api.twitter.com/1.1/account/verify_credentials.json", {}, oauth ) user = JSON.parse(response.body) # Just saving user info to database user.merge! dbtoken db.lock { db[user["screen_name"]] = user } result = user else result = nil end db.close return result end # Generic request method used by methods above def request(method, uri, params, oauth) uri = URI.parse(uri.to_s) # always use SSL, you are dealing with other users data http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true # uncomment line below for debug purposes #http.set_debug_output($stdout) req = (method == :post ? Net::HTTP::Post : Net::HTTP::Get).new(uri.request_uri) req.body = params.to_a.map { |x| "#{x[0]}=#{x[1]}" }.join("&") req["Host"] = "api.twitter.com" # Oauth magic is done by simple_oauth gem. # This gem is enable you to use any HTTP lib # you want to connect in OAuth enabled APIs. # It only creates the Authorization header value for you # and you can assign it wherever you want # See https://github.com/laserlemon/simple_oauth req["Authorization"] = SimpleOAuth::Header.new(method, uri.to_s, params, oauth) http.request(req) end end end 

有关详细说明, 请访问: https : //github.com/lfcipriani/sign_in_with_twitter_sample