【问题标题】:Access Token for SharePoint REST API calls through AAD?通过 AAD 调用 SharePoint REST API 的访问令牌?
【发布时间】:2021-11-10 16:56:41
【问题描述】:
我目前正在构建一个 .NET Core 应用程序,该应用程序执行对以下内容的直接 SharePoint REST 调用:contoso.sharepoint.com/sites/shipment/_api/search/query?querytext='...'
.NET Core 应用程序已在应用程序注册中注册。如何检索访问令牌? (由于某种原因,MS Graph API 无法进行这些调用,因此尝试使用 SPO REST API)
【问题讨论】:
标签:
azure
.net-core
sharepoint
azure-active-directory
microsoft-graph-api
【解决方案1】:
您可以像这样使用证书方式获取令牌:
private static async Task<string> GetToken()
{
string applicationId = "xxx";
string tenantId = "contoso.onmicrosoft.com";
X509Certificate2 certificate = new X509Certificate2(@"C:\certificate.pfx", "password");
IConfidentialClientApplication confApp = ConfidentialClientApplicationBuilder.Create(applicationId)
.WithAuthority($"https://login.microsoftonline.com/{tenantId}")
.WithCertificate(certificate) // This is just a local method that gets the certificate on my machine
.Build();
var scopes = new[] { "https://contoso.sharepoint.com/.default" };
var authenticationResult = await confApp.AcquireTokenForClient(scopes).ExecuteAsync();
return authenticationResult.AccessToken;
}
【解决方案2】:
我将以下代码用于公共客户端应用程序
public async Task<string> GetTokenAsync()
{
var clientId = "{client_id}";
var tenantId = "{tenant_id}";
var instance = "https://login.microsoftonline.com";
IPublicClientApplication clientApp = PublicClientApplicationBuilder.Create(clientId)
.WithAuthority($"{instance}/{tenantId}")
.WithDefaultRedirectUri()
.Build();
var accounts = await clientApp.GetAccountsAsync();
var firstAccount = accounts.FirstOrDefault();
var scopes = new[] { "https://contoso.sharepoint.com/.default" };
var userName = "{user}";
SecureString password = ...;
AuthenticationResult authResult;
try
{
authResult = await clientApp.AcquireTokenSilent(scopes, firstAccount).ExecuteAsync();
}
catch (MsalUiRequiredException ex)
{
authResult = await clientApp
.AcquireTokenByUsernamePassword(scopes, userName, password)
.ExecuteAsync();
}
return authResult.AccessToken;
}