MS Graph api 用户身份验证失败

时间:2021-04-24 02:12:58

标签: azure-active-directory microsoft-graph-api

我开始使用 MS Graph API。我需要一个用户干预最少的登录示例;如果可能,最多只运行一次,并且第一次运行应用程序。示例 GraphTutorial 应用 (https://github.com/microsoftgraph/msgraph-training-dotnet-core/tree/main/demo) 似乎每次运行时都需要用户干预,并且需要手动输入代码。

谢谢

问候

1 个答案:

答案 0 :(得分:2)

要在不登录的情况下调用图形 api,可以使用客户端凭据流。 Microsoft 还为其提供了 sample code。我还测试并挑选了一些关键代码,如下所示:

using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using Microsoft.Identity.Client;

namespace WebApplication4clientflow.Controllers
{
    public class HelloController : Controller
    {
        public async Task<string> Index()
        {
            IConfidentialClientApplication app;
            app = ConfidentialClientApplicationBuilder.Create("azure_ad_app_clientid")
                    .WithClientSecret("client_secret_of_your_app")
                    .WithAuthority(new Uri("https://login.microsoftonline.com/tenant_name.onmicrosoft.com"))
                    .Build();

            AuthenticationResult result = null;
            string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
            result = await app.AcquireTokenForClient(scopes)
                    .ExecuteAsync();
            return result.AccessToken;
        }
    }
}

通过上面的代码,我们可以生成访问令牌来调用图形api,但请注意,它不适用于那些没有support application permission的api,如下所示:

enter image description here

如果您遇到更多问题,请随时告诉我。