据我所知,您无法通过 AAD 请求带有客户端/秘密令牌的 SharePoint REST API。但它适用于证书。下面一步一步来:
由于我遇到了同样的问题,我将在这里发布我是如何通过带有 MSAL 的 AAD 应用程序(OAuth v2 和 AAD v2 端点)连接到 SharePoint API 的。它在 C# 中。
首先,我只成功了一个证书(据我所知,客户端/秘密方法不起作用)。
创建证书
出于测试目的,我创建了一个带有“New-PnPAzureCertificate”的自签名证书,如下所示:
$secPassword = ConvertTo-SecureString -String "MyPassword" -AsPlainText -Force
$cert = New-PnPAzureCertificate -OutCert "CertSPUser.cer" -OutPfx "CertSPUser.pfx" -ValidYears 10 -CertificatePassword $secPassword -CommonName "CertSPUser" -Country "FR" -State "France"
(-Country 和 -State 参数对测试无关紧要)
(它也适用于New-SelfSignedCertificate 命令)
注册证书
然后,您必须在您的 AAD 应用程序(“.cer”文件)中上传证书:
配置应用程序 API 权限
之后,您必须授权 SharePoint API:
尝试通过 Daemon App (C#) 访问
NuGet 包(希望我什么都没忘记)
- Microsoft.SharePointOnline.CSOM
- Microsoft.Identity.Client
为了让事情顺利进行,您必须分 3 个步骤来完成(我已经简化了,但您最好通过一些 try/catch 将操作分成方法)
获取 Pfx 证书
对于这一步,我强烈建议使用 KeyVault(请参阅帖子底部的链接)
string certPath = System.IO.Path.GetFullPath(@"C:\PathTo\CertSPUser.pfx");
X509Certificate2 certificate = new X509Certificate2(certPath, "MyPassword", X509KeyStorageFlags.MachineKeySet);
获取令牌
string tenantId = "yourTenant.onmicrosoft.com" // Or "TenantId"
string applicationId = "IdOfYourAADApp"
IConfidentialClientApplication confApp = ConfidentialClientApplicationBuilder.Create(applicationId)
.WithAuthority($"https://login.microsoftonline.com/{tenantId}")
.WithCertificate(certificate)
.Build();
string sharePointUrl = "https://yourSharePoint.sharepoint.com" // Or "https://yourSharePoint-admin.sharepoint.com" if you want to access the User Profile REST API
var scopes = new[] { $"{sharePointUrl}/.default" };
var authenticationResult = await confApp.AcquireTokenForClient(scopes).ExecuteAsync();
string token = authenticationResult.AccessToken;
测试您的连接
ClientContext ctx = new ClientContext(sharePointUrl);
ctx.ExecutingWebRequest += (s, e) =>
{
e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + token;
};
Web web = ctx.Web;
ctx.Load(web);
ctx.Load(web);
ctx.ExecuteQuery();
// OR if you connect to User Profile ("yourSharePoint-admin.sharepoint.com")
/*
PeopleManager peopleManager = new PeopleManager(ctx);
var personProperties = peopleManager.GetUserProfileProperties("i:0#.f|membership|employee.mail@tenant.onmicrosoft.com");
ctx.ExecuteQuery();
*/
如果我没有遗漏任何内容,您应该获得一些网络/用户信息! ?
希望对你有帮助。
编辑(2020 年 11 月 14 日):即使在我的 API 权限屏幕截图中,我添加了应用程序权限“User.ReadWrite.All”,如果您尝试更新用户配置文件,它不会工作。要解决此问题,您必须将 AAD 应用程序注册为旧版 SharePoint 仅应用程序主体(客户端 ID/机密)。更多信息here.
感谢 @laurakokkarinen 和 @mmsharepoint 的文章真正帮助了我(here 和 here)