首页 文章

OneDrive API:未经身份验证,必须经过身份验证才能使用'/drive'语法

提问于
浏览
0

我正在使用OneDrive api在我的Ruby on Rails应用程序中上传文件,并且OneDrive API开始使用endpoint / drive / root:/#:/ content在上传文件时出现未经身份验证的错误 . 错误如下:

{"error"=>{"code"=>"unauthenticated", "message"=>"Must be authenticated to use '/drive' syntax"}}

然后我使用范围files.readwrite offline_access跟随OneDrive文档获得了一个新的refresh_token .

对于OneDrive身份验证,我发送POST请求到 endpoints https://login.microsoftonline.com/common/oauth2/v2.0/token以使用带有以下标头和正文的refresh_token获取access_token:

headers = { 'Content-Type' => 'application/x-www-form-urlencoded' }
body = {
  'client_id'     => "<Client ID>",
  'grant_type'    => "refresh_token",
  'redirect_uri'  => "<Redirect URI>",
  'client_secret' => "<Client Secret>",
  'refresh_token' => "<Refresh Token>",
}

我是否使用正确的 endpoints 从refresh_token获取access_token?

我用来将文件上传到OneDrive的基础uri是https://api.onedrive.com/v1.0

任何人都可以请帮助我为什么我得到未经验证的错误或如何使用'/ drive'语法进行身份验证?

提前致谢!

1 回答

  • 0

    Solved:

    在我的情况下,我使用"Code flow"进行身份验证,并使用以下url获取参数中的 code

    https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=CLIENT_ID&scope=files.readwrite offline_access&response_type=code&redirect_uri=REDIRECT_URI
    

    访问上面的url打开了重定向url,其中包含一个很长的 code 参数,我用它来获取 access_tokenrefresh_token 但是access_token无法将文件上传到OneDrive并重新调整"unauthenticated"错误 .

    经过研究,我发现我用于获取OneDrive身份验证 code 的网址是Microsoft Graph . Microsoft帐户的正确URL如下:

    https://login.live.com/oauth20_authorize.srf?client_id=CLIENT_ID&scope=onedrive.readwrite offline_access&response_type=code&redirect_uri=REDIRECT_URI
    

    在浏览器中访问上面的URL会将我重定向到带有代码参数的页面,但它是像 K9vb4e786-afg6-1a3b-1234-12abc01234ca 这样的小代码 .

    我使用此代码使用以下POST请求获取 access_tokenrefresh_token

    body = {
      client_id: "CLIENT_ID",
      redirect_uri: "REDIRECT_URI",
      client_secret: "CLIENT_SECRET",
      code: "CODE",
      grant_type: "authorization_code"
    }
    headers = { 'Content-Type' => 'application/x-www-form-urlencoded' }
    
    r=HTTParty.post('https://login.live.com/oauth20_token.srf', headers: headers, body: body)
    

    此请求返回了access_token和refresh_token作为响应 . 我使用 refresh_token 在每个请求中获得 access_token 并成功上传文件 .

    Conclusion: 我使用的是Microsoft Graph身份验证过程,即https://docs.microsoft.com/en-us/onedrive/developer/rest-api/getting-started/graph-oauth,这是不正确的 . 然后我遵循Microsoft帐户身份验证,即https://docs.microsoft.com/en-us/onedrive/developer/rest-api/getting-started/msa-oauth解决了该问题 .

    Update:

    后来我使用Office-365商业帐户进行OneDrive文件上传 . 对于此帐户,OneDrive身份验证过程是不同的,即https://docs.microsoft.com/en-us/onedrive/developer/rest-api/getting-started/aad-oauth并且它有效 .

相关问题