Microsoft Live授权GET请求返回Net :: HTTPBadRequest 400

时间:2015-04-07 11:55:43

标签: ruby post get http-error

我正在关注Microsoft live connect API documentation以授权我的用户访问onedrive。我正在尝试建立代码流认证。我按照描述获得了AUTHORIZATION_CODE。现在,我试图在ACCESS_TOKEN的帮助下得到{<1}}:

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而不是POST。 所以,我在ruby中创建了一个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它的完美值。

1 个答案:

答案 0 :(得分: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)