Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add `Authorization Bearer` hash to Net::HTTP post request (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?

like image 768
tim_xyz Avatar asked Dec 08 '16 06:12

tim_xyz


1 Answers

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)
like image 126
Alok Swain Avatar answered Sep 25 '22 00:09

Alok Swain