如何通过应用注册Client ID和Secret获取SharePoint列表项?403问题排查
核心问题分析及解决点
1. 令牌受众不匹配
你当前获取的是Microsoft Graph的访问令牌(scope设置为https://graph.microsoft.com/.default),但调用的是SharePoint自身的REST API(/_api/web/...),两者的令牌受众(aud声明)不匹配:
- Graph令牌的受众是
https://graph.microsoft.com - SharePoint REST API要求令牌受众为目标站点根URL(如
https://contoso.sharepoint.com/sites/TargetSite)或租户SharePoint根域(https://<tenant>.sharepoint.com)
修复方案:
- 若继续使用SharePoint REST API:修改token请求的scope为
https://<tenant>.sharepoint.com/.default,确保令牌受众匹配 - 若改用Microsoft Graph API:调用端点改为
https://graph.microsoft.com/v1.0/sites/{site-id}/lists/{list-id}/items,此时原Graph令牌可正常使用
2. 未对目标站点显式授予应用权限
sites.selected(Graph权限)或Site.Selected(SharePoint权限)是需绑定到特定站点的权限,仅在应用注册中添加权限无法生效,必须通过API给目标站点分配应用访问权限:
示例Graph API请求(需站点管理员权限或应用有Sites.FullControl.All权限):
POST https://graph.microsoft.com/v1.0/sites/{site-id}/permissions Content-Type: application/json { "roles": ["read"], "grantedToIdentities": [{ "application": { "id": "你的应用clientId", "displayName": "应用名称" } }] }
3. 权限类型与API不匹配
若坚持使用SharePoint REST API,需确认应用注册中添加的是SharePoint的Site.Selected权限,而非Graph的sites.selected权限——Graph权限仅对Graph API生效,SharePoint REST API无法识别。
代码调整示例(改用Graph API)
如果切换到Graph API获取列表项,可修改get_sharepoint_list_content方法:
def get_sharepoint_list_content(self, site_id, list_id, **kwargs): filter_query = kwargs.get('filter_query', '') columns = kwargs.get('columns', 'id') top = kwargs.get('top', '') url = f"https://graph.microsoft.com/v1.0/sites/{site_id}/lists/{list_id}/items?$select={columns}&$filter={filter_query}&$top={top}" headers = { 'Accept': 'application/json', 'Authorization': f'Bearer {self.token}' } list_items = [] while url: response = requests.get(url, headers=headers) lista = response.json() list_items.extend(lista.get('value', [])) url = lista.get('@odata.nextLink', '') return list_items
内容的提问来源于stack exchange,提问作者Roni Antonio
相关产品推荐
相关产品推荐

