Search code examples
ruby-on-railsrubyjwtopenurl

How to download a file from a URL that requires a 'Bearer Token' from the Rails console?


I have the URL for a file but it is protected and requires a JWT token.

This won't work.

require 'open-uri'
open('image.png', 'wb') do |file|
  file << open('http://example.com/image.png').read
end

Is there a way to pass headers on that request?


Solution

  • You can add a header in the second parameter as described in https://ruby-doc.org/stdlib-2.3.1/libdoc/open-uri/rdoc/OpenURI.html.

    require 'open-uri'
    
    token = "f00"
    
    url = "http://via.placeholder.com/150"
    
    open('image.png', 'wb') do |file|
      file << open(url, "Authorization" => "Bearer #{token}").read
    end