2

I have a Rails app with OAuth API. I'm using Doorkeeper gem for the OAuth 2 authentication. My API allows posting messages with image file attachments. I'd like to test it from Ruby console. Now, the problem is - how do I sign the post requests with the access token?

Doorkeeper wiki provides a tutorial on testing API with the OAuth2 gem itself. The problem there is that OAuth2 class doesn't provide ways of posting multiparted messages with the file attachments (as far as I got it).

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

Then again there is multipart-post gem, which allows posting files as attachment to the Rails API. But I don't get how to sign such request with an access_token, and to pass the Doorkeeper authentication.

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

So what is the proper way of posting multiparted messages to Rails API signed with the access_token?

2 Answers 2

2

The oauth2 gem seems to not support multipart upload. Check this issue: https://github.com/intridea/oauth2/issues/81

An workaround would include the access_token in your parameters, either as a query string or as a header. Following the example in 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
Sign up to request clarification or add additional context in comments.

Comments

0

You also have to explicitly set the ssl on if you have this error:

EOFError in YourController#youraction 
end of file reached

Exemple

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.