【问题标题】:Rails: Testing OAuth API by posting multiparted messages with file attachmentRails:通过发布带有文件附件的多部分消息来测试 OAuth API
【发布时间】:2013-04-09 21:37:03
【问题描述】:

我有一个带有 OAuth API 的 Rails 应用程序。我正在使用 Doorkeeper gem 进行 OAuth 2 身份验证。我的 API 允许发布带有图像文件附件的消息。我想从 Ruby 控制台测试它。现在,问题是 - 我如何使用访问令牌签署发布请求?

Doorkeeper wiki 提供了使用 OAuth2 gem 本身测试 API 的教程。问题在于 OAuth2 类不提供使用文件附件发布多部分消息的方法(据我所知)。

https://github.com/applicake/doorkeeper/wiki/Testing-your-provider-with-OAuth2-gem

还有 multipart-post gem,它允许将文件作为附件发布到 Rails API。但我不知道如何使用 access_token 签署此类请求,并通过 Doorkeeper 身份验证。

https://github.com/nicksieger/multipart-post

那么,将多部分消息发布到使用 access_token 签名的 Rails API 的正确方法是什么?

【问题讨论】:

    标签: ruby-on-rails-3 http oauth-2.0 multipart


    【解决方案1】:

    oauth2 gem 似乎不支持分段上传。检查这个问题:https://github.com/intridea/oauth2/issues/81

    一种解决方法是在参数中包含access_token,作为查询字符串或标题。按照 README 中的示例:

    require 'net/http/post/multipart'
    
    url = URI.parse('http://www.example.com/upload')
    File.open("./image.jpg") do |jpg|
      req = Net::HTTP::Post::Multipart.new url.path,
        "file" => UploadIO.new(jpg, "image/jpeg", "image.jpg")
    
      # here you include the token in headers
      req['Authorization'] = "Bearer #{THE_ACCESS_TOKEN}"
      res = Net::HTTP.start(url.host, url.port) do |http|
        http.request(req)
      end
    end
    

    【讨论】:

      【解决方案2】:

      如果出现此错误,您还必须明确设置 ssl:

      EOFError in YourController#youraction 
      end of file reached
      

      示例

      require 'net/http/post/multipart'
      
      url = URI.parse('http://www.example.com/upload')
      File.open("./image.jpg") do |jpg|
        req = Net::HTTP::Post::Multipart.new url.path, 
          "file" => UploadIO.new(jpg, "image/jpeg", "image.jpg")
      
        # here you include the token in headers
        req['Authorization'] = "Bearer #{THE_ACCESS_TOKEN}"
      
        http = Net::HTTP.new(url.host, url.port)
      
        #mention the use of ssl
        http.use_ssl = true
      
        res = http.request(req)
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-31
        • 2015-10-16
        相关资源
        最近更新 更多