Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Basic Base64 Authentication

I'm trying to replicate this GET curl request:

curl -D- -X GET -H "Authorization: Basic dGVzdEB0YXByZXNlYXJjaC5jb206NGMzMTg2Mjg4YWUyM2ZkOTY2MWNiNWRmY2NlMTkzMGU="
-H "Content-Type: application/json" http://staging.example.com/api/v1/campaigns

The auth is generated with an email + an api key this way in Ruby:

auth = "Basic" + Base64::encode64("[email protected]:4c3186288ae23fd9661cb5dfcce1930e")

What's the best way to replicate this in Ruby/Rails?

Here's what I've been trying:

    auth = "Basic" + Base64::encode64("[email protected]@:4c3186288ae23fd9661cb5dfcce1930e")
    uri = URI.parse("https://www.staging.example.com/api/v1/campaigns")

    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE

    request = Net::HTTP::Get.new(uri.request_uri)
    request.env['HTTP_AUTHORIZATION'] = auth
    response = http.request(request)

    puts response.body

Based off of a few other SO's and blogs I've found, but then I get undefined method 'env' for #<Net::HTTP::Get GET> back.

Any ideas how I can set that so the message comes out like this?

Authorization: Basic dGVzdEB0YXByZXNlYXJjaC5jb206NGMzMTg2Mjg4YWUyM2ZkOTY2MWNiNWRmY2NlMTkzMGU=
like image 203
Tom Hammond Avatar asked Aug 23 '15 23:08

Tom Hammond


2 Answers

request['Authorization'] =  "Basic " + Base64::encode64("[email protected]@:4c3186288ae23fd9661cb5dfcce1930e")
like image 152
aromero Avatar answered Oct 23 '22 13:10

aromero


Here's a more straightforward way, using request.basic_auth to handle all the messy details:

request = Net::HTTP::Post.new(uri)
request.basic_auth(username, password)
http = Net::HTTP.new(uri.host, uri.port)
response = http.request(request)
like image 29
David Hempy Avatar answered Oct 23 '22 11:10

David Hempy