Reputation: 1552
I'm trying to access a REST interface from the Kentico CMS and I don't seem to be able to access it properly in my Rails application. I can access it in the browser, and I get a username/password authentication box that pops up, which then gives me the JSON back after entering the proper credentials.
In my Rails application, I am using rest-client and trying to access via the following:
username = 'username_here'
password = 'password_here'
page_url = 'page_url_here'
resource = RestClient::Resource.new(page_url, :username => username, :password => password)
response = resource.get
Also tried:
resource = RestClient::Resource.new(page_url)
resource.head :Authorization => Base64.encode64(username) + ":" + Base64.encode64(password)
response = resource.get
Both give me an error of connection refused. Kentico's documentation says each request needs to be sent with an authorization header like so:
Authorization: Basic <enter Base64-encoded <username>:<password> here>
So I assume I must not be sending the headers correctly, or possibly the rest-client gem is just not up to the task. I am open to using other gems or entirely different approaches. Any help is appreciated!
I was able to get rid of the connection refused error by changing the second example to the following:
resource = RestClient::Resource.new(page_url)
resource.head :Authorization => "Basic " + Base64.encode64("%s:%s" % [username, password])
However, I am now getting a 405 Method Not Allowed error. Is there something else in the header the browser is sending that rest-client is not?
Upvotes: 0
Views: 528
Reputation: 1552
I did a little more Googling and found RestClient is just a wrapper for Net::HTTP standard library.
http://www.ruby-forum.com/topic/1648618
Scrolling down this page more, I found what I was looking for to do Basic Authentication:
uri = URI('http://example.com/index.html?key=value')
req = Net::HTTP::Get.new(uri.request_uri)
req.basic_auth 'user', 'pass'
res = Net::HTTP.start(uri.hostname, uri.port) {|http|
http.request(req)
}
puts res.body
To me, this is way easier than trying to figure out how to make RestClient do what you want. Hopefully, this can help someone else in the future not waste their time with it like I did :)
Upvotes: 1
Reputation: 14412
I believe the first example should be
resource = RestClient::Resource.new(page_url, :user => username, :password => password)
response = resource.get
That is user instead of username.
Upvotes: 0