Microsoft Live authorization GET request returns Net::HTTPBadRequest 400 - ruby

I am following Microsoft live connect API documentation to authorize my user to access onedrive. I am trying to stablish code flow authentication. I got the AUTHORIZATION_CODE as described. Now, I am trying to get the ACCESS_TOKEN with the help of that:
In Microsoft live connect API documentation, its said for getting ACCESS_TOKEN we need to provide a request such as,
POST https://login.live.com/oauth20_token.srf
Content-type: application/x-www-form-urlencoded
client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&client_secret=CLIENT_SECRET&
code=AUTHORIZATION_CODE&grant_type=authorization_code
I provided the same request using ruby and got a error:
#<Net::HTTPBadRequest 400 Bad Request readbody=true>
Then I found in microsoft forum, that the request is GET not POST.
so, I created a GET request in ruby as follow:
access_code =params["code"]
uri = URI.parse("https://login.live.com/oauth20_token.srf")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true if uri.scheme == 'https'
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.read_timeout = 500
req = Net::HTTP::Get.new("https://login.live.com/oauth20_token.srf",
initheader = {'Content-Type' =>'application/x-www-form-urlencoded'})
data = URI.encode_www_form({'client_id'=> 'my_client_id' ,
'redirect_uri' =>'my_redirect_url',
'client_secret' =>'my_client_secret',
'code'=>access_code, 'grant_type' =>'authorization_code'})
req.body = data
res = http.start { |http| http.request(req) }
When I run this I am getting the same HTTPBadRequest 400 error.
Note: I have checked the values of CLIENT_ID,REDIRECT_URI,CLIENT_SECRET,AUTHORIZATION_CODE it's all perfect.

I regret seeing that forum to solve this problem and wasted my time.
actually POST request will do good in this situation as show in thier documentation.
This is how I got the response,
uri = URI.parse("https://login.live.com/oauth20_token.srf")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
req = Net::HTTP::Post.new("https://login.live.com/oauth20_token.srf")
req.content_type = "application/x-www-form-urlencoded"
data = URI.encode_www_form({'client_id'=> 'my_client_id' , 'redirect_uri' =>'my_redirect_ui', 'client_secret' =>'my_client_secret', 'code'=>access_code, 'grant_type' =>'authorization_code'})
req.body = data
response = http.request(req)

Related

Ruby - HTTPS get calls with headers

Have a query on making a https Get call with headers. I tried the following
uri = URI.parse("https:\\www.someurl.com")
req = Net::HTTP::Get.new(uri)
# Following is where I am adding the header
req['Auth'] = "Bearer" + #token
response = Net::HTTP.start(uri.host,uri.port) do |http|
request = Net::HTTP::Get.new uri.request_uri
http.request request
end
puts(response.body)
I see the following error
400 The plain HTTP request was sent to HTTPS port
I tried searching and what I have found is that Net::HTTP.get supports https calls but without headers.
The call that I am making is via API gateway, so I will have to add a token in the header.
Any help is much appreciated. Thanks in advance.
You need to use use_ssl: true.
uri = URI('https://secure.example.com/some_path?query=string')
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
request = Net::HTTP::Get.new(uri)
request['Authentication'] = "Bearer %s" % #token
http.request(request)
end

Sending a http post request in ruby [duplicate]

So here's the request using curl:
curl -XPOST -H content-type:application/json -d "{\"credentials\":{\"username\":\"username\",\"key\":\"key\"}}" https://auth.api.rackspacecloud.com/v1.1/auth
I've been trying to make this same request using ruby, but I can't seem to get it to work.
I tried a couple of libraries also, but I can't get it to work.
Here's what I have so far:
uri = URI.parse("https://auth.api.rackspacecloud.com")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new("/v1.1/auth")
request.set_form_data({'credentials' => {'username' => 'username', 'key' => 'key'}})
response = http.request(request)
I get a 415 unsupported media type error.
You are close, but not quite there. Try something like this instead:
uri = URI.parse("https://auth.api.rackspacecloud.com")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new("/v1.1/auth")
request.add_field('Content-Type', 'application/json')
request.body = {'credentials' => {'username' => 'username', 'key' => 'key'}}.to_json
response = http.request(request)
This will set the Content-Type header as well as post the JSON in the body, rather than in the form data as your code had it. With the sample credentials, it still fails, but I suspect it should work with real data in there.
There's a very good explanation of how to make a JSON POST request with Net::HTTP at this link.
I would recommend using a library like HTTParty. It's well-documented, you can just set up your class like so:
class RackSpaceClient
include HTTParty
base_uri "https://auth.api.rackspacecloud.com/"
format :json
headers 'Accept' => 'application/json'
#methods to do whatever
end
It looks like the main difference between the Ruby code you placed there, and the curl request, is that the curl request is POSTing JSON (content-type application/json) to the endpoint, whereas request.set_form_data is going to send a form in the body of the POST request (content-type application/x-www-form-urlencoded). You have to make sure the content going both ways is of type application/json.
All others are too long here is a ONE LINER:
Net::HTTP.start('auth.api.rackspacecloud.com', :use_ssl => true).post(
'/v1.1/auth', {:credentials => {:username => "username",:key => "key"}}.to_json,
initheader={'Content-Type' => 'application/json'}
)
* to_json needs require 'json'
OR if you want to
NOT verify the hosts
be more readable
ensure the connection is closed once you're done
then:
ssl_opts={:use_ssl => true, :verify_mode => OpenSSL::SSL::VERIFY_NONE}
Net::HTTP.start('auth.api.rackspacecloud.com', ssl_opts) { |secure_connection|
secure_connection.post(
'/v1.1/auth', {:credentials => {:username => "username",:key => "key"}}.to_json,
initheader={'Content-Type' => 'application/json'}
)
}
In case it's tough to remember what params go where:
SSL options are per connection so you specify them while opening the connection.
You can reuse the connection for multiple REST calls to same base url. Think of thread safety of course.
Header is a "request header" and hence specified per request. I.e. in calls to get/post/patch/....
HTTP.start(): Creates a new Net::HTTP object, then additionally opens the TCP connection and HTTP session.
HTTP.new(): Creates a new Net::HTTP object without opening a TCP connection or HTTP session.
Another example:
#!/usr/bin/ruby
require 'net/http'
require 'json'
require 'uri'
full_url = "http://" + options[:artifactory_url] + "/" + "api/build/promote/" + options[:build]
puts "Artifactory url: #{full_url}"
data = {
status: "staged",
comment: "Tested on all target platforms.",
ciUser: "builder",
#timestamp: "ISO8601",
dryRun: false,
targetRepo: "#{options[:target]}",
copy: true,
artifacts: true,
dependencies: false,
failFast: true,
}
uri = URI.parse(full_url)
headers = {'Content-Type' => "application/json", 'Accept-Encoding'=> "gzip,deflate",'Accept' => "application/json" }
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri, headers)
request.basic_auth(options[:user], options[:password])
request.body = data.to_json
response = http.request(request)
puts response.code
puts response.body

Can you make a YouTube analytics API request using Net::HTTP in Ruby?

Assuming my access_token and my TEST_CHANNEL_ID are correct, shouldn't this request work?
I'm getting a 404 error, am I missing some parameter?
uri = URI.parse("https://www.googleapis.com")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new("/youtube/analytics/v1/reports")
request.body = URI.encode_www_form({"Authorization" => "Bearer #{access_token}", "ids" => "channel==#{TEST_CHANNEL_ID}", "start-date" => "2015-07-01", "end-date" => "2015-07-20", "metrics" => "views"})
response = http.request(request)
It's worth mentioning that I obtained my access_token with a refresh_token authorized for all youtube api scopes
If you're passing the access token as a URL parameter, the name of the parameter should be "access_token" and you don't need the "Bearer" part of the string; it would just be:
request.body = URI.encode_www_form({"access_token" => "#{access_token}", "ids" => "channel==#{TEST_CHANNEL_ID}", "start-date" => "2015-07-01", "end-date" => "2015-07-20", "metrics" => "views"})
You only use the Authorization: Bearer {whatever}form if you're setting the access token in the request header.
Here's the documentation on this.

Ruby Sinatra create post request without PEM and OpenSSL::SSL::VERIFY_NONE

I try create POST request with SSL but without OpenSSL::SSL::VERIFY_NONE because it is opend up security attacks and without PEM certificate.
But I catch problems, my ruby code for send POST request:
post '/test/test1' do
cross_origin
post_data = request.body.read
res_Data = JSON.parse(post_data)
userName = res_Data['username']
#responseFromServer=''
uri = URI('https://test.com/test1')
Net::HTTP.start(uri.host, uri.port,
:use_ssl => uri.scheme == 'https',
:verify_mode => OpenSSL::SSL::VERIFY_NONE) do |http|
request = Net::HTTP::Post.new uri.request_uri
request.basic_auth 'aa', 'bb'
request.body = {'username' =>userName}.to_json
response = http.request request
#responseFromServer = response.body.to_s
end
newJson = JSON.parse(#responseFromServer)
status_msg = newJson['status']['status_msg']
if (status_msg == "Success")
return 'true'
end
return 'false'
end
It is method worked but he use OpenSSL::SSL::VERIFY_NONE. How to create method for send POST request without OpenSSL::SSL::VERIFY_NONE and PEM sertificate?
EDIT
SSL/HTTPS request
Update: There are some good reasons why this code example is bad. It introduces a potential security vulnerability if it's essential you use the server certificate to verify the identity of the server you're connecting to. There's a fix for the issue though!
require "net/https"
require "uri"
uri = URI.parse("https://secure.com/")
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)
response = http.request(request)
response.body
response.status
response["header-here"] # All headers are lowercase
SSL/HTTPS request with PEM certificate
require "net/https"
require "uri"
uri = URI.parse("https://secure.com/")
pem = File.read("/path/to/my.pem")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.cert = OpenSSL::X509::Certificate.new(pem)
http.key = OpenSSL::PKey::RSA.new(pem)
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
request = Net::HTTP::Get.new(uri.request_uri)
My question: How to create POST method without PEM and OpenSSL::SSL::VERIFY_NONE?
This question is quite misleading, but I try my best to figure it out. Here is my advise:
Do you want to connect to a service that is only available through https and you do not care if the certificate is valid?
Then you can use :verify_mode => OpenSSL::SSL::VERIFY_NONE when initializing the Net::HTTP client.
You will have some kind of transport security, but you cannot be sure the server you are talking to is the one you think it is. You are vulnerable.
Do you want to connect to a service that is available both through https and http, and you do not care about transport security?
Then you should use the http://... endpoint.
Do you want to connect to a service and you care about transport security?
Then you should definitely use the https://... endpoint.
Do not override :verify_mode!
If you are getting certificate verification errors, make sure you have the correct Certificate Authority installed on your system.

Jira Rest API - How to login

I've been going through this guide: JIRA API Documentation and can't seem to figure out how to simply authenticate to the API if you're using gmail to login to Jira. I'm hoping to use the REST API within my ruby app in order to link github and jira
Edit: Code:
uri = URI.parse("https://<address>.jira.com/rest/api/2/issue/<issue-name>")
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)
request["user"] = "<username>"
request["password"] = "<password>"
#jira_response = http.request(request)
With the above code; I get a HTTP unauthorized response.
Resolved by using;
request.basic_auth 'username', 'password'
request["Content-Type"] = "application/json"
instead of:
request["user"] = "<username>"
request["password"] = "<password>"
A while ago I wrote a small skeleton app for using the Jira api. It may or may not be helpful for you. See https://github.com/vaneyckt/SimpleJira.

Resources