通过 AAD 调用 SharePoint REST API 的访问令牌?

Access Token for SharePoint REST API calls through AAD?

我目前正在构建一个 .NET Core 应用程序,它执行直接 SharePoint REST 调用:contoso.sharepoint.com/sites/shipment/_api/search/query?querytext='...'

.NET Core 应用程序已在应用程序注册中注册。如何检索访问令牌? (出于某种原因,MS Graph API 无法进行这些调用,因此尝试使用 SPO REST API)

您可以使用证书方式获取令牌,如下所示:

    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;
    }

我正在为 public 客户端应用程序使用以下代码

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;
}