使用 Express.js 将文件上传到共享点,但收到“仅支持应用程序的令牌”错误

问题描述 投票:0回答:1

我尝试在 Express.js 中实现通过 Azure 上传文件到 SharePoint 的功能。

我从 Azure AD 获得了正确的令牌(我认为),但是当我尝试将文件上传到 SharePoint 时

我一直收到“仅支持应用程序的令牌”。我不知道是API权限设置错误还是哪里可能。

希望有人能帮助我!谢谢!!!!

这就是我获取令牌并尝试在API中调用上传文件时使用的方式

async function getAccessToken() {
    const tokenEndpoint = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;
  
    const requestBody = new URLSearchParams({
      grant_type: "client_credentials",
      client_id: clientId,
      client_secret: clientSecret,
      scope: `${resource}/.default`
    });
  
    try {
        const response = await axios.post(tokenEndpoint, requestBody, {
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
          });
          
          return response.data.access_token;
    } catch (error) {
      console.error('Error obtaining token:', error.response.data);
      throw new Error('Failed to obtain access token');
    }
  }

这是我尝试将文件上传到 SharePoint 但出现错误

async function uploadFileToSharePoint(filePath, fileName, folderPath) {
    const accessToken = await getAccessToken(); // Get the access token
    const file = fs.readFileSync(filePath); // Read the file from disk

    try {
        const response = await axios.put(
            `${siteUrl}/_api/web/GetFolderByServerRelativeUrl(${folderPath})/Files/add(url=${fileName},overwrite=true)`,
            file,
            {
                headers: {
                    'Authorization': `Bearer ${accessToken}`,
                    'Accept': 'application/json;odata=verbose',
                    'Content-Type': 'application/octet-stream'
                }
            }
        );

        return response.data.d; // Return the response data from SharePoint
    } catch (error) {
        console.error('Error uploading to SharePoint:', error.response ? error.response.data : error.message);
        throw new Error('File upload to SharePoint failed.');
    }
}

这是我的错误“上传到 SharePoint 时出错:仅应用程序令牌不受支持。”

我的期望是可以成功上传文件到SharePoint

node.js azure express sharepoint
1个回答
0
投票

注意:使用客户端凭据流生成 SharePoint 的访问令牌仅接受通过客户端证书请求的访问令牌,而不接受客户端密钥。参考这个MsDoc

因此,您必须使用用户交互流或使用支持客户端凭据流(支持机密)的 Microsoft Graph API。

  • 因此,通过证书而不是秘密来生成访问令牌,请参阅 Martin Loitzl 的博客

使用以下端点授权用户:

https://login.microsoftonline.com/TenantID/oauth2/v2.0/authorize?
&client_id=ClientID
&response_type=code
&redirect_uri=https://jwt.ms
&response_mode=query
&scope=https://Domain.sharepoint.com/.default
&state=12345

enter image description here

使用以下参数生成访问令牌

https://login.microsoftonline.com/TenantID/oauth2/v2.0/token

grant_type:authorization_code
client_id:ClientID
client_secret:ClientSecret
scope:https://Domain.sharepoint.com/.default
code:code
redirect_uri:https://jwt.ms

enter image description here

否则,请使用 Microsoft Graph API。参考这个MsDoc

参考:

教程:在 Node.js 和 Express Web 应用程序中登录用户 - Microsoft 身份平台 |微软

© www.soinside.com 2019 - 2024. All rights reserved.