3

我正在铁轨上尝试我的手红宝石。大多数情况下,我是在 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 文档解释了这个 3-legged 身份验证,但我仍然无法弄清楚。

我已阅读https://dev.twitter.com/docs/auth/3-legged-authorizationhttps://dev.twitter.com/docs/auth/implementing-sign-twitter 不幸的是,在互联网上没有找到任何 ruby​​ 代码用一步一步的例子来解释。

用户点击时应该使用什么链接打开推特认证页面Link your twitter account。这里的任何人都可以用我上面的伪凭证编写一些伪代码来实现我从开始到结束这个工作流程的目标吗?谢谢。

更新:

我从请求请求令牌开始

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

4

2 回答 2

4

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

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

    发布https://api.twitter.com/oauth/request_token

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

  2. 您将从 twitter 收到 am oauth_token 和 oauth_token_secret。

  3. 将用户重定向到

    https://api.twitter.com/oauth/authorize?oauth_token=[token_received_from_twitter]

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

  4. 当用户授权您的应用程序时,他们将被重定向到您的回调 url,并且 oauth_token 和 oauth_verifier 附加到 url。IE

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

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

    发布 https://api.twitter.com/oauth/access_token

    使用您的消费者密码和在步骤 2 中收到的令牌密码对您的请求进行签名。

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

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

于 2013-05-13T10:26:26.550 回答
2

Hope you solved your problem by this time, but I built this sample Sign in with Twitter ruby web app that provide all explanation you need to do this integration. Below there's a class that implements all necessary methods with comments:

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

More detailed explanation at: https://github.com/lfcipriani/sign_in_with_twitter_sample

于 2013-11-28T12:49:24.557 回答