2015-04-07 72 views
3

我在關注Microsoft live connect API documentation以授權我的用戶訪問onedrive。我正在嘗試建立代碼流身份驗證。如上所述,我得到了AUTHORIZATION_CODE。現在,我試圖用的是幫助,以獲得ACCESS_TOKENGET請求返回#<Net :: HTTPBadRequest 400 Bad Request readbody = true>

Microsoft live connect API documentation,其表示爲獲得ACCESS_TOKEN我們需要提供的請求,例如,

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  

我使用Ruby提供相同的請求並得到了一個錯誤:

#<Net::HTTPBadRequest 400 Bad Request readbody=true> 

然後我microsoft forum發現,該請求是GET無法發佈。 所以,我在紅寶石創建了一個GET請求如下:

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) } 

當我運行此我得到同樣的HTTPBadRequest 400錯誤。

注意:我檢查了CLIENT_ID,REDIRECT_URI,CLIENT_SECRET,AUTHORIZATION_CODE的值是完美的。

回答

6

我很遺憾地看到那個論壇解決了這個問題,浪費了我的時間。

實際上POST請求在這種情況下會表現得很好,正如他們的文檔中所示。

這是我得到的迴應,

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)