向 sharepoint 询问列表中的项目时未授权访问异常



我正在尝试访问我的 SharePoint 网站中的列表项目。我在"https://XXXXXX.sharepoint.com/sites/XXXXX/_layouts/15/appregnew.aspx"页面上创建了一个客户端ID和一个secretId。然后我在"https://XXXXX.sharepoint.com/sites/XXXXX/_layouts/15/appinv.aspx"页面上创建访问规则。 在此页面上,我设置了访问规则的 XML 代码,如下所示:

<AppPermissionRequests><AppPermissionRequest 
Scope="http://sharepoint/content/sitecollection" 
Right="FullControl"/></AppPermissionRequests>

我创建规则并在下一页上确认。

在我的应用程序中,我使用此代码获取令牌

let payload = `grant_type=client_credentials
&client_id=${clientId}@${tenantId}
&client_secret=${clientSecret}
&resource=${resource}/${domain}@${tenantId}`;
let authOptions = {
hostname: 'accounts.accesscontrol.windows.net',
path: `/${tenantId}/tokens/OAuth/2`,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(payload)
}
};
let req = https.request(authOptions, res => {...})

然后我这样做是为了获取列表中的项目:

let listOptions = {
hostname: 'XXXXX.sharepoint.com',
path: '/sites/XXX/_api/lists/getbytitle('MyList')/items',
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `bearer ${accessToken}`,
'Accept': 'application/json'
}
};
let req = https.request(listOptions, res => {
res.setEncoding('utf8');
let stringResult = '';
res.on('data', chunk => {
stringResult += chunk.toString();
});

SharePoint 始终返回此错误

"{"error":{"code":"-2147024891, System.UnauthorizedAccessException","message":{"lang":"en-US","value":"Access denied. You do not have permission to perform this action or access this resource."}}}"

我终于找到了为什么它不起作用。我需要添加仅允许应用策略:

<AppPermissionRequests AllowAppOnlyPolicy="true">
<AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="FullControl" />

最新更新