drbrain / net-http-persistent

Thread-safe persistent connections with Net::HTTP
http://seattlerb.rubyforge.org/net-http-persistent
339 stars 117 forks source link

http authentication #27

Closed matthiasjakel closed 12 years ago

matthiasjakel commented 12 years ago

When I try the following code then I get an 401 status code. I looks like http authentication isn't supported or how can I activate it?

uri = URI 'http://user:password@example.com/awesome/web/service'
http = Net::HTTP::Persistent.new 'my_app_name'
response = http.request uri
drbrain commented 12 years ago

HTTP authentication isn't supported by net-http-persistent and won't be added.

Supporting HTTP authentication properly is beyond the scope of net-http-persistent which is primarily oriented around managing HTTP connections. In order to implement HTTP authentication properly net-http-persistent would need to keep a database of users, passwords, realms and URIs to avoid leaking login credentials accidentally. (Mechanize implements this across five classes for proper parsing of authentication challenges and proper handling of credentials.)

I'm working on a separate library that combines the HTTP features such as authentication, redirection, compression, etc. from mechanize with net-http-persistent for inclusion in ruby (which will also be released as a gem).

In the mean time, to get you started, take a look at this code in mechanize to get you started:

https://github.com/tenderlove/mechanize/blob/master/lib/mechanize/http/agent.rb#L504-516

drbrain commented 12 years ago

If you wish to use basic authentication you can set it up per request:

require 'net/http/persistent'

uri = URI 'http://localhost/foo'

http = Net::HTTP::Persistent.new

req = Net::HTTP::Get.new uri.request_uri
req.basic_auth 'username', 'password'

http.request uri, req

If you need to use NTLM or Digest authentication it will require more work, but the idea is the same. Create the request object and pass it along with the URI to #request.

matthiasjakel commented 12 years ago

thank you!

ajsharp commented 11 years ago

Thanks for the example @drbrain. It might be worth considering adding this to the docs somewhere. IMO basic auth is a pretty common use case, especially for interacting with APIs. Just my $0.02.