Rest client post with username and password - ruby

curl --request POST \
--url https://example.com/token/grant \
--header 'password: password' \
--header 'username: user' \
--data '{"app_key":"my_app_key","app_secret":"my_app_secret"}'
I am trying to get an equivalent ruby code for the above curl request with rest client.
I have tried:
auth = 'Basic ' + Base64.encode64( "#{AA['user_name']}:#{AA['password']}" ).chomp
response = RestClient.post'https://example.com/token/grant', {"app_key":"my_app_key","app_secret":"my_app_secret"}, { 'Authorization' => auth , :accept => :json, 'Content-Type': 'application/json' }
response = JSON.parse(response)
It did not work.
2nd try:
RestClient.post 'https://example.com/token/grant', {"app_key":"my_app_key","app_secret":"my_app_secret"}.to_json, {'username': 'username', 'password': 'password', content_type: 'application/json'}
Also did not work.
I have checked username and password is correct.
It showing that username is missing in the header.
Thanks in advance.

As per the description it seems like when running the request using RestClient the header is action is unable to process the header (username since it is the first key in the header hash).
I have executed the below command on a custom code and it worked.
RestClient.post 'https://example.com/token/grant', {"app_key":"my_app_key","app_secret":"my_app_secret"}.to_json, {username: 'username', password: 'password', content_type: 'application/json'}
Note: I have just updated the representation of header keys passed in the header hash.

I have tried with Rest client. It did not work. Then I also tried Faraday, Net HTTP nothing works.
Then I have tried with curb. It works.
require 'curb'
request_path= 'https://example.com/token/grant'
payload = {
app_key: 'app_key',
app_secret: 'app_secret'
}
http = Curl.post(request_path, payload.to_json) do |http|
http.headers['username'] = 'user_name'
http.headers['password'] = 'password'
http.headers['Content-Type'] = 'application/json'
end
JSON.parse(http.body_str)

Related

Google PeopleApi in Ruby - CreateContact method invalid argument

I'm using the 'google-api-client' gem to connect into Google People API from my Ruby Application. https://github.com/googleapis/google-api-ruby-client
I've managed to get other methods working (list_person_connections, get_people, delete_person_contact and update_person_contact) but I can't get the createContact (create_person_contact) method from google people API to work.
After I send the post, I get this error:
400 Caught error badRequest: Request contains an invalid argument.
This is an example code to create a contact with just the name field (I will want to actually also send email and phoneNumbers parameters on the body, but it also returns the same error, so I'm giving you the simplest example here):
require 'google/apis/content_v2'
require "google/apis/people_v1"
require "googleauth"
require "googleauth/stores/file_token_store"
require "fileutils"
require 'google/apis/people_v1'
require 'google/api_client/client_secrets'
client_secrets = Google::APIClient::ClientSecrets.load 'credentials.json'
auth_client = client_secrets.to_authorization
auth_client.update!(
:scope => ['https://www.googleapis.com/auth/contacts', 'https://www.googleapis.com/auth/contacts.other.readonly'],
:redirect_uri => 'http://localhost:3102/oauth2callback',
:client_id => 'MY CLIENT ID',
:client_secret => 'MY CLIENT SECRET',
#:authorization_uri => 'https://accounts.google.com/o/oauth2/auth',
:additional_parameters => {"access_type" => "offline", "include_granted_scopes" => "true"})
auth_uri = auth_client.authorization_uri.to_s
auth_client.code = 'THE AUTH CODE'
auth_client.fetch_access_token!
people = Google::Apis::PeopleV1::PeopleServiceService.new
people.authorization = auth_client
body = {:names => [{:givenName => "TEST"}]}
people.create_person_contact(body, person_fields: 'names')
The problem is just those 2 last lines. When called, they send this with the body:
Sending HTTP post https://people.googleapis.com/v1/people:createContact?personFields=names
And it returns the error above, no matter what I change.
In the documentation, you can actually try and test this exact same code and it works.
https://developers.google.com/people/api/rest/v1/people/createContact?authuser=2&apix=true&apix_params=%7B%22personFields%22%3A%22names%22%2C%22resource%22%3A%7B%22names%22%3A%5B%7B%22givenName%22%3A%22TEST%22%7D%5D%7D%7D
You can fill the request body form exactly as I did, and hit EXECUTE And it will give a 200 OK response.
I can't see what the invalid argument is. This is also exactly what I do on the update_person_contact method and that one works.
I've searched the internet and can't find anyone with a similar problem and the documentation just doesn't say much: https://www.rubydoc.info/github/google/google-api-ruby-client/Google%2FApis%2FPeopleV1%2FPeopleServiceService:create_person_contact
Anyone have any idea to help me?
Thank you.
After almost giving up, I decided to try the CURL option. So I copied it from their 'Try this API' page I linked above and translated it to Ruby code.
curl --request POST \
'https://people.googleapis.com/v1/people:createContact?personFields=names' \
--header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--data '{"names":[{"givenName":"TEST"}]}' \
--compressed
And you know what? It worked.
So I think this gem doesn't work for this particular case (it is google-api-client v: 0.42.2 and 0.43.0 in case you are wondering), but if you came here to find a solution to the same problem, this is what worked for me, and I hope it helps you:
(this replace those last 2 lines on my code):
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://people.googleapis.com/v1/people:createContact?personFields=names")
request = Net::HTTP::Post.new(uri)
request.content_type = "application/json"
request["Authorization"] = "Bearer #{people.authorization.access_token}"
request["Accept"] = "application/json"
request.body = JSON.dump({
"names" => [
{
"givenName" => "TEST"
}
],
"emailAddresses" => [
{
"value" => "testemail#test.com"
}
],
"phoneNumbers" => [
{
"value" => "12345678"
}
]
}
)
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
response.code
response.body
It's not ideal, but it got the job done today.
EDIT: After writing this I just realized even the 'personFields' parameter is useless, since the body got the right fields.
You can see in my answer, I only called the 'names' fields on the URI, but all those 3 fields were correctly there on my new contact (name, email and phone number) after it got saved. So that's also probably useless/optional.

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.

HTTPs Request in Ruby with parameters

I'm trying to pull data from a RESTful JSON web service which uses https. They provided a Curl example which works no problem; however, I'm trying to run the query in Ruby and I'm not a Ruby developer.
Any help much appreciated!
cURL example:
curl -G "https://api.example.com/v1/query/" \
-H "Accept: application/vnd.example.v1+hal+json" \
-u "$API_KEY:$API_SECRET" \
-d "app_id=$APP_ID" \
-d "days=3" \
-d "metrics=users" \
-d "dimensions=day"
My attempt in Ruby which is resulting in a HTTPUnauthorized 401:
require 'net/https'
require 'uri'
# prepare request
uri = URI.parse("https://api.example.com/v1/query/")
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, {
'Accept' => 'application/vnd.example.v1+hal+json',
'api_key' => 'api_secret',
'app_id' => 'app_id',
'days' => '3',
'metrics' => 'users',
'dimensions' => 'day'})
response = http.request(request)
response.body
response.status
response["header-here"] # All headers are lowercase
# Analyze the response
if response.code != "200"
puts "Error (status-code: #{response.code})\n#{response.body}"
print 0
else
print 1
end
** Update **
As per feedback below, I've installed Typhoeus and updated the request. Now I'm getting through. Thanks all!
request = Typhoeus::Request.new(
"https://api.example.com/v1/query/",
userpwd: "key:secret",
params: {
app_id: "appid",
days: "3",
metrics: "users",
dimensions: "day"
},
headers: {
Accept: "application/vnd.example.v1+hal+json"
}
)
First you need to realize that:
'Accept' => 'application/vnd.example.v1+hal+json'
is a header, not a parameter.
Also:
$API_KEY:$API_SECRET
is basic HTTP authentication, not a parameter.
Then, take my advice and go with a better Ruby HTTP client:
https://github.com/lostisland/faraday (preferred, a wrapper for the bellow)
https://github.com/typhoeus/typhoeus
https://github.com/geemus/excon
Update:
Try the following from IRB:
Typhoeus::Config.verbose = true # this is useful for debugging, remove it once everything is ok.
request = Typhoeus::Request.get(
"https://api.example.com/v1/query/",
userpwd: "key:secret",
params: {
app_id: "appid",
days: "3",
metrics: "users",
dimensions: "day"
},
headers: {
Accept: "application/vnd.example.v1+hal+json"
}
)
curl's -u sends the Authorization header. so your 'api_key' => 'api_secret', should be replaced with this one(once again, its http header, not parameter).
"Authorization" => "Basic ".Base64.encode64("api_key:api_secret")
## require "base64"

Rest-Client: how to post multipart/form-data?

I have to implement the curl POST request below listed, in Ruby, using Rest-Client.
I have to:
send params in header;
send params (that do not contain a file) as multipart/form-data:
$ curl -X POST -i -H "Authorization: Bearer 2687787877876666686b213e92aa3ec7e1afeeb560000000001" \
https://api.somewhere.com/endpoint -F sku_id=608399
How can I translate the curl request using the RestClient rubygem?
Reading documentation (multipart paragraph): https://github.com/rest-client/rest-client
I coded as:
#access_token = 2687787877876666686b213e92aa3ec7e1afeeb560000000001
url = 'https://api.somewhere.com/endpoint'
req = { authorization: "Bearer #{#access_token}"}
RestClient.post url, req, {:sku_id => 608399, :multipart => true}
But I get a server error; is the Ruby code above correct?
Thanks a lot,
Giorgio
Since I had trouble understanding the example Dmitry showed, here is an example for creating a Multipart request to upload an image:
response = RestClient.post 'https://yourhost.com/endpoint',
{:u_id => 123, :file => File.new('User/you/D/cat.png', 'rb'), :multipart => true},
{:auth_token => xyz5twblah, :cookies => {'_cookie_session_name' => cookie}}
It's code not valid for RestClient implementation.
headers should follow after payload.
module RestClient
def self.post(url, payload, headers={}, &block)
...
end
end
UPDATE
#access_token should be a string "2687787877876666686b213e92aa3ec7e1afeeb560000000001"
then
RestClient.log = 'stdout'
RestClient.post url, {:sku_id => 608399, :multipart => true}, req
and log
RestClient.post "https://api.somewhere.com/endpoint", "--330686\r\nContent-Disposition: form-data; name=\"sku_id\"\r\n\r\n608399\r\n--330686--\r\n", "Accept"=>"*/*; q=0.5, application/xml", "Accept-Encoding"=>"gzip, deflate", "Authorization"=>"Bearer 2687787877876666686b213e92aa3ec7e1afeeb560000000001", "Content-Length"=>"79", "Content-Type"=>"multipart/form-data; boundary=330686"

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.

Resources