【问题标题】:MS Graph throws 401 when uploading a file to another user’s OneDrive share将文件上传到其他用户的 OneDrive 共享时,MS Graph 抛出 401
【发布时间】:2021-10-12 17:44:58
【问题描述】:

我已经在这个简单的事情上工作了 3 天,我需要一些明智的建议:

我需要从 Node.js 将文件发送到另一个用户的 OneDrive 共享。

  • 在 Azure 中,我确保我拥有适当的权限: Files.ReadWrite.All 类型为 Application Files.ReadWrite.All 类型为 Delegated

  • 我还添加了可选声明: act - 用户在租户中的帐户状态 - 令牌类型:访问

然后我通过调用 MSAL ConfidentialClientApplication 获取访问令牌,然后获取令牌ByClientCredential,如下所示:

function generateTokenPromise() {
  let config = {
    auth: {
      clientId: applicationId,
      authority: msOnlineBaseUrl + '/' + tenantId,
      clientSecret: clientSecretValue,
    },
    system: {
      loggerOptions: {
        loggerCallback(loglevel, message, containsPii) {
          console.log(message);
        },
        piiLoggingEnabled: false,
        logLevel: msal.LogLevel.Verbose,
      }
    }
  };

  // Create msal application object
  let cca = new msal.ConfidentialClientApplication(config);

  let clientCredentialRequest = {
    tenant: tenantId, 
    client_id: applicationId,
    scopes: ["https://graph.microsoft.com/.default"],
    client_secret: clientSecretValue,
    azureRegion: "centralus",
    skipCache: true,
    grant_type: "client_credentials",
  };

  return cca.acquireTokenByClientCredential(clientCredentialRequest)
}

令牌很好,它允许我在其他用户的帐户上工作:

  • 我可以读取根文件夹和子文件夹的内容。
  • 我可以读取驱动器项目的信息,包括文件和文件夹。
  • 我可以在其他帐户中创建文件夹。

但是,当我尝试创建文件时,应用程序给了我一个 HTTP 错误代码 401:未经授权的客户端错误状态响应。这没有任何意义。我有正确的身份验证,令牌是好的,否则它不允许执行其他功能。

为了创建请求,我使用了带有缓冲区的 Node.js FormData。我剥离了代码,试图让它工作:

function uploadBinaryFile(req, res) {
  let token
  generateTokenPromise()
  .then(tokenResponse => {
    // token = tokenResponse.accessToken
    return receiveBinaryFilePromise(req)
  })
  .then(async buffer => {
    let microsoftUserId = 'LidiaH@appsname.onmicrosoft.com'
    let foundFolderName = 'found-folder'
    let foundFolderId = '01S2X...TOETQ'  // this is the found-folder's Folder Id
    let filename = "new-file.jpg"
    let url = new URL(`/users/${microsoftUserId}/drive/items/${foundFolderId}:/${filename}:/content`, msGraphBaseUrl)
    // let url = new URL(`/users/${microsoftUserId}/drive/root:/${foundFolderName}/${filename}:/content`, msGraphBaseUrl)
    
    let form = new FormData()
    // form.append('uploadFile',  buffer)
    form.append('field', 'a,b,c', 'blah.csv');    // TODO: this is a test, use the buffer later

    let headersConfig = {
      "Authorization": `Bearer ${token}`,
      ...form.getHeaders()
    }
    return axios({
      method: 'post',
      url: url.toString(),
      data: form,
      headers: headersConfig 
    })
  })
  .then(thing => {
    console.log('Success!')
  })
  .catch(error => {
    console.error(error)
  })
 }

我怀疑 axios 正在做什么来启动请求。我已经尝试更改 headerConfig 和 URL,但我的想法和时间都用完了。

我也阅读了有关 FormData 的信息,但我认为它很好。

你知道怎么做吗?你能推荐一篇文章吗?解决方法?通往隧道尽头的指路明灯?

谢谢 路易斯。

【问题讨论】:

  • 您使用的是POST,而文档建议使用PUT。您是否尝试过通过 Postman 上传文件?
  • @MarioVarchmin,你完全正确。我将其更改为 PUT,然后在 Postman 中尝试。我将文件作为二进制文件添加到正文中,然后尝试,在修复请求后,它起作用了!谢谢!
  • 我很高兴听到它现在对您有用。
  • 您好@MarioVarchmin,您能否发布您的建议作为答案,因为它对 DigitalOnion 有效,它将帮助其他社区成员。
  • @ansumanBal-MT:完成!

标签: node.js axios azure-active-directory microsoft-graph-api access-token


【解决方案1】:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多