Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Microsoft Live authorization GET request returns Net::HTTPBadRequest 400

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.

like image 714
Balaji Radhakrishnan Avatar asked Mar 20 '26 08:03

Balaji Radhakrishnan


1 Answers

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)
like image 74
Balaji Radhakrishnan Avatar answered Mar 23 '26 02:03

Balaji Radhakrishnan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!