Add `Authorization Bearer` hash to Net::HTTP post request (Ruby)
Asked Answered
R

2

9

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?

Radical answered 8/12, 2016 at 6:11 Comment(0)
G
12

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)
Grommet answered 8/12, 2016 at 6:49 Comment(1)
Do not put the colon after BearerPlaque
L
0

Here's another style:

require 'json'
require 'net/http'
require 'uri'

url = 'http://localhost:8080/places'
token = 'eyJ0eXAiO...'
payload = [{'uuid' => '0514b...', 'name' => 'Athens'}]

uri = URI.parse(url)
request = Net::HTTP::Post.new(uri)
request.content_type = 'application/json'
request['Authorization'] = "Bearer #{token}"
request.body = payload.to_json
response = Net::HTTP.start(
  uri.host,
  uri.port,
  use_ssl: uri.scheme == 'https'
) do |http|
  http.request(request)
end

if response.is_a?(Net::HTTPSuccess)
  puts JSON.parse(response.body)
else
  puts "POST failed: #{response.code} - #{response.message}"
end

Feel free to test with url = 'https://httpbin.org/post'.

See What’s the best way to handle exceptions from Net::HTTP? for error handling.

Lianna answered 16/2 at 20:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.