'How to access the page protected by basic auth using Faraday?

I have a php page I want to access and that page is protected by basic auth. I know the url and username/password, they are listed below in code:

url = 'https://henry.php' # note that it is a php website
username = 'foo'
password = 'bar'

Faraday provide basic auth function, their doc says that I should use the following code:

connection = Faraday.new(url: url) do |conn|
  conn.basic_auth(username, password)
end 

I want to get the response body of the above url to make sure that the basic auth indeed succeed and I can access the content, but I don't know how to. I tried each of the following ways but none of them work:

connection.body
connection.response.body
connection.env.response.body

# or

r = connection.get
r.body
r.response.body
r.env.response.body

# or

r = connection.get '/'
r.body
r.response.body
r.env.response.body

What is the proper way to get the body?

Note:

In browser, I access https://henry.php directly and browser prompt me a box asking my username and password and I enter them and I can see the content - I can see the details I have is correct and it should work (this is because browser knows how to do basic auth), but I just can't figure out how to do it in code using Faraday.



Solution 1:[1]

The Faraday gem comes with a number of plugins (middleware) that make HTTP requests simpler and more customizable. In Ruby, basic authentication might be difficult. Let's have a look at it;

require "faraday"

request_helper = Faraday.new(url: 'example.com') do |builder|
                builder.use Faraday::Request::BasicAuthentication, client_key, secret_key
             end

# you make HTTP requests using `request_helper` since basic auth is configured

response = request_helper.get('/myendpoit')

You must obtain tokens by proving client and secret keys when using an API such as the Stripe API. We can give client and secret keys as inputs to the Faraday::Request::BasicAuthentication middleware to establish basic authentication using the same approach as before.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adif_Sgaid