Somehow HTTParty returns 401 where CURL works fine. Not sure how to pass token in headers.
Working (200):
curl http://localhost:3020/api/products -H 'Authorization: Token token="111"'
Not working (401):
HTTParty.get('http://localhost:3020/api/products', headers: {"Authorization: Token token" => '111'})
I have tried with just "Authorization" => '111'
and "token" => '111'
but same result.
Bearer token Bearer tokens enable requests to authenticate using an access key, such as a JSON Web Token (JWT). The token is a text string, included in the request header. In the request Authorization tab, select Bearer Token from the Type dropdown list.
What is an Access Token? A credential that can be used by an application to access an API. Access Tokens can be either an opaque string or a JSON Web Token (JWT) . They inform the API that the bearer of the token has been authorized: to access a particular service or services.
The bearer token is a cryptic string, usually generated by the server in response to a login request. The client must send this token in the Authorization header when making requests to protected resources: Authorization: Bearer <token>
Managed to get it working as follows.
HTTParty.get("http://localhost:3020/api/products", headers: {"Authorization" => "Token token=\"111\""})
This also works if you want to set headers of the class dynamically, this example is for obtaining the Authorization token for Dun and Bradstreet
require 'httparty'
require 'certified'
class DnbAuth
include HTTParty
debug_output $stdout
base_uri "https://maxcvservices.dnb.com/rest/Authentication"
def initialize(ct,u,p)
self.class.headers 'Content-type' => "#{ct}"
self.class.headers 'x-dnb-user' => "#{u}"
self.class.headers 'x-dnb-pwd'=> "#{p}"
end
def token()
response = self.class.post("/")
end
end
ct = 'text/xml'
u = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
p = 'xxxxxx'
xx = DnbAuth.new(ct,u,p)
puts xx.token.message
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With