Skip to content
Advertisement

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.

Advertisement

Answer

Answering my own question:

Instead of just:

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

you should remember to use an adapter:

connection = Faraday.new(url: url) do |conn|
  conn.adapter Faraday.default_adapter # make requests with Net::HTTP
  conn.basic_auth(username, password)
end

because Faraday is an interface, it does not do the actual work of making connection and request, the adapter does that, so you need it for it to work.

Then, to get ther response body you want, you can just:

response = connection.get
response.body
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement