使用Rest API删除SharePoint站点时遇受众验证失败问题排查
问题
尝试通过API删除SharePoint站点,操作流程如下:
- 获取Access Token的请求:
curl --location 'https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --data-urlencode 'client_id={clientId}' \ --data-urlencode 'client_secret={clientSecret}' \ --data-urlencode 'grant_type=client_credentials' \ --data-urlencode 'scope=https://graph.microsoft.com/.default'
- 解析Token后,包含的角色:
"roles": [ "Sites.Selected", "Sites.Read.All", "Sites.ReadWrite.All", "Sites.Manage.All", "Files.ReadWrite.All", "Files.Read.All", "Sites.FullControl.All" ]
- 执行删除站点的SharePoint REST API请求:
curl --location 'https://{tenant}.sharepoint.com/sites/{testSite}/_api/SPSiteManager/delete' \ --header 'Accept: application/json;odata.metadata=none' \ --header 'odata-version: 4.0' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer {bearerToken}' \ --data '{ "siteId": "{siteId}" }'
执行后收到错误:
{ "error_description": "Exception of type 'Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException' was thrown." }
原因与解决方案
核心问题:Token受众不匹配
你获取的Access Token受众(aud字段)是https://graph.microsoft.com,但调用的是SharePoint的REST API,该API要求Token的受众为你的SharePoint站点域名(比如https://{tenant}.sharepoint.com),两者不匹配导致验证失败。
解决方案1:更换Token获取的Scope
修改获取Token请求中的scope参数为SharePoint站点的默认范围,示例如下:
curl --location 'https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --data-urlencode 'client_id={clientId}' \ --data-urlencode 'client_secret={clientSecret}' \ --data-urlencode 'grant_type=client_credentials' \ --data-urlencode 'scope=https://{tenant}.sharepoint.com/.default'
使用这个新生成的Token重新执行删除请求即可。
更优方案:使用Microsoft Graph API删除站点
既然你的Token已拥有Sites.FullControl.All等Graph权限,推荐直接使用Graph API删除站点,无需切换Token受众,请求示例如下:
curl --location --request DELETE 'https://graph.microsoft.com/v1.0/sites/{siteId}' \ --header 'Authorization: Bearer {bearerToken}'
该方式更统一,且符合微软推荐的API调用规范。
内容的提问来源于stack exchange,提问作者Danny Verdel
相关产品推荐
相关产品推荐

