Search code examples
ruby-on-railsbasic-authentication

Rails http GET request with no ssl verification and basic auth


I am trying to make a http get request as specified in the title. What I've written:

uri = URI.parse("https://myaddress.com")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE 
@data = http.get(uri.request_uri)

The request is sent where I want it to be sent and I receive an Unauthorized response (as expected, because I did not specify the basic auth).

I've tried

http.basic_auth 'user', 'pass'

But there's no such method for the type of my http variable. How can I add the auth details?

Update: I tried to use something like here RUBY - SSL, Basic Auth, and POST, but after replacing Post with Get, I cannot use the 'use_ssl', nor 'verify_mode' attributes (I get no such attribute error).

Update 2: I figured out that I can set the 'use_ssl' attribute on a Net::HTTP object and the 'basic_auth' on a Net::HTTP::Get object. Now the question is how can I make them work together?


Solution

  • Well, I ended up finding an answer. Maybe this will help others:

    url = URI.parse('https://myaddress.com')
    req = Net::HTTP::Get.new(url.path)
    req.basic_auth 'user', 'pass'
    
    sock = Net::HTTP.new(url.host, url.port)
    sock.use_ssl = true
    sock.verify_mode = OpenSSL::SSL::VERIFY_NONE
    
    resp = sock.start {|http| http.request(req) }