首页 > 解决方案 > 通过 AAD 调用 SharePoint REST API 的访问令牌?

问题描述

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

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

标签: azure.net-coresharepointazure-active-directorymicrosoft-graph-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;
    }

推荐阅读