Add `Authorization Bearer` hash to Net::HTTP post request (Ruby) - ruby

How can I add Authorization Bearer to a POST request with Net::HTTP?
I can only find help for "basic authentication" in the documentation.
req.basic_auth 'user', 'pass'
Source: https://docs.ruby-lang.org/en/2.0.0/Net/HTTP.html#class-Net::HTTP-label-Basic+Authentication
I'm trying to replicate a curl that would look like:
> curl 'http://localhost:8080/places' -d '{"_json":[{"uuid":"0514b...",
> "name":"Athens"}]}' -X POST -H 'Content-Type: application/json' -H
> 'Authorization: Bearer eyJ0eXAiO...'
Currently I've gotten to:
require 'net/http'
require 'net/https'
require 'uri'
uri = URI('http://localhost:8080/places')
res = Net::HTTP.post_form(uri, '_json' => [{'uuid': '0514b...', 'name':'Athens'}])
But I'm having trouble figuring out how to add the Authentication: Bearer... part.
Does anyone have experience with this?

I dont think you can add custom headers with the post_form method. You can add it with post method. Try the code below:
uri = URI("http://localhost:8080/places")
params = [{'uuid': '0514b...', 'name':'Athens'}]
headers = {
'Authorization'=>'Bearer foobar',
'Content-Type' =>'application/json',
'Accept'=>'application/json'
}
http = Net::HTTP.new(uri.host, uri.port)
response = http.post(uri.path, params.to_json, headers)

Related

Convert Hash to specific string format in ruby

I would like to convert a hash: {"key1"=>"value1", "key2"=>"value2"} into a string which looks like this: '[{"key1" : "value1","key2" : "value2"}]'
Background: I'm making an API call from my rails Controller.
The curl equivalent of this request is curl -X POST -H 'Content-Type: application/json' -i 'valid_uri' --data '[{"key1" : "value1","key2" : "value2"}]'
So, to convert this in ruby, I tried the following:
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse(VALID_URI)
header = {'Content-Type' => 'application/json'}
data = {"key1"=>"value1", "key2"=>"value2"}
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri, header)
request.body = Array.wrap(data1.to_s.gsub('=>',':')).to_s
response = http.request(request)
However, the format of request.body doesn't match the format of data in curl request which results in Net::HTTPBadRequest 400 Bad Request
Can someone please explain how can I achieve this? TIA
just use the json module:
require "json"
h=[{"key1"=>"value1", "key2"=>"value2"}]
string=h.to_json # => [{"key1":"value1","key2":"value2"}]

How to use httparty instead of net/http or curl

I have a curl request which works
curl -X GET -k 'https://APIADDRESSHERE' -u 'USERNAME:PASSWORD' -H 'Content-Type: application/json'
I can also get this working in ruby:
require 'net/http'
require 'uri'
require 'openssl'
uri = URI.parse("https://APIADDRESSHERE")
request = Net::HTTP::Get.new(uri)
request.basic_auth("USERNAME", "PASSWORD")
request.content_type = "application/json"
req_options = {
use_ssl: uri.scheme == "https",
verify_mode: OpenSSL::SSL::VERIFY_NONE,
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
However when I try this with httparty I keep getting a 401 error saying:
An Authentication object was not found in the SecurityContext This request requires HTTP authentication.
I have tried a lot of variations of the following but I'm stuck.
response = HTTParty.get('https://APIURLHERE', {"headers": { "Authorization:" => "BASE64ENCODEDUSERNAMEANDPASSWORD", "Content-Type" => "application/json" }})
Have you tried the following?
response = HTTParty.get('https://APIURLHERE', headers: { "Authorization:" => "BASE64ENCODEDUSERNAMEANDPASSWORD", "Content-Type" => "application/json" })
Ok I made a simple mistake somewhere along the way because the original solution from the similar post worked... Dont know how it didnt work 50 times last time I was working on this but it was clearly an error on my part somewhere.

Microsoft Azure get access token API not working with cURL/Ruby but works with powershell

I am simply trying to get an access token from client id, client secret and tenant ID. Following powershell command works successfully
Invoke-RestMethod -Uri https://login.microsoftonline.com/TENANT/oauth2/token?api-version=1.0 -Method Post -Body #{"grant_type" = "client_credentials"; "resource" = "https://management.core.windows.net/"; "client_id" = "CLIENTID"; "client_secret" = "SECRET" }
But this curl doesn't work
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "grant_type=client_credentials&resource=https://management.core.windows.net/&client_id=CLIENTID&client_secret=SECRET" "https://login.microsoftonline.com/TENANT/oauth2/token?api-version=1.0"
Neither this ruby script
require 'json'
require 'typhoeus'
url = 'https://login.microsoftonline.com/TENANT/oauth2/token?api-version=1.0'
params = "grant_type=client_credentials&resource=https://management.core.windows.net/&client_id=CLIENTID&client_secret=SECRET"
HEADERS = {
"Content-Type" => "application/x-www-form-urlencoded"
}
resp = Typhoeus::Request.post(url, body: params, headers: HEADERS)
I am following this link. Any clues why neither of curl / ruby works ?
Thanks in advance
I tried to reproduce your issue successfully, and I discovered that the issue was caused by curl without OpenSSL and Typhoeus request without setting ssl_verifypeer: false.
So please follow this to check via curl --version and install openssl libraries on your environment.
Here is my sample code.
require "typhoeus"
url = 'https://login.microsoftonline.com/<tanet-id>/oauth2/token?api-version=1.0'
params = "grant_type=client_credentials&resource=https://management.core.windows.net/&client_id=<client-id>&client_secret=<client-key>"
headers = {
"Content-Type" => "application/x-www-form-urlencoded"
}
request = Typhoeus.post(url, body: params, headers: headers, ssl_verifypeer: false)
puts request.code, request.body
Hope it helps.

Having problems translating a curl command to Ruby Net::HTTP

This is a call to a Usergrid-stack web app to create a new application:
curl -H "Authorization: Bearer <auth_token>" \
-H "Content-Type: application/json" \
-X POST -d '{ "name":"myapp" }' \
http://<node ip>:8080/management/orgs/<org_name>/apps
Here's my Ruby code:
uri = URI.parse("http://#{server.ipv4_address}:8080/management/orgs/#{form.org_name}/apps")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri, {'Authorization' => 'Bearer #{form.auth_token}', 'Content-Type' => 'application/json'})
request.set_form({"name" => form.app_name})
command.output.puts uri.request_uri
response = http.request(request)
Currently I'm getting this response from the server:
{\"error\":\"auth_unverified_oath\",\"timestamp\":1383613556291,\"duration\":0,\"exception\":\"org.usergrid.rest.exceptions.SecurityException\",\"error_description\":\"Unable to authenticate OAuth credentials\"}"
In this line--
request = Net::HTTP::Post.new(uri.request_uri, {'Authorization' => 'Bearer #{form.auth_token}', 'Content-Type' => 'application/json'})
Try changing that authorization string to "Bearer #{form.auth_token}"--with double quotes. String interpolation only works with double-quoted strings.

curl request in ruby

How would I make the following curl request in ruby?
curl -k -X GET -H "Content-Type: application/xml" -H "Accept: application/xml" -H "X-OFFERSDB-API-KEY: demo" 'http://testapi.offersdb.com/distribution/beta/offers?radius=10&postal_code=30305'
I'm having difficulty with some of the headers.
require 'net/http'
url = 'http://testapi.offersdb.com/distribution/beta/offers?radius=10&postal_code=30305'
mykey = 'demo'
request = Net::HTTP.new(url)
request.request_head('/', 'X-OFFERSDB-API-KEY' => mykey)
puts request
I think you need to create a request object, instead of an HTTP object. Then set headers on it.
require 'net/http'
url = 'http://testapi.offersdb.com/distribution/beta/offers?radius=10&postal_code=30305'
mykey = 'demo'
uri = URI(url)
request = Net::HTTP::Get.new(uri.path)
request['Content-Type'] = 'application/xml'
request['Accept'] = 'application/xml'
request['X-OFFERSDB-API-KEY'] = mykey
response = Net::HTTP.new(uri.host,uri.port) do |http|
http.request(request)
end
puts response
Source: http://ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net/HTTPHeader.html

Resources