2015-04-07 116 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) 
相关问题