如何在 ASP.NET Core Web 应用程序中获取 Microsoft Graph 客户端?

问题描述 投票:0回答:1

背景

我有一个可用的 ASP.NET Core Web 应用程序,它使用 Entra ID 身份验证:

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddInMemoryTokenCaches();

为了使此身份验证正常工作,我创建了一个 Azure 应用程序注册,并且身份验证的配置包含相应的客户端 ID、客户端密钥和租户 ID。 我已经添加了 Azure 应用程序注册所需的图形权限。

我想在此 Web 应用程序中调用 Graph API 例如:

var meeting = new OnlineMeeting() { Subject = "demo meeting" };
var result = await graphClient.Me.OnlineMeetings.PostAsync(meeting);

我发现的所有示例代码要么使用设备流来获取

graphClient
,要么使用折旧或破坏更改的身份验证来创建
graphClient

问题

如何创建

graphClient

c# azure-active-directory microsoft-graph-api openid-connect microsoft-graph-teams
1个回答
0
投票

GraphServiceClient
构造函数将
TokenProvider
作为第一个参数,因此您可以使用
ClientSecretCredential
,如下所示(来自Microsoft文档):

// The client credentials flow requires that you request the
// /.default scope, and pre-configure your permissions on the
// app registration in Azure. An administrator must grant consent
// to those permissions beforehand.
var scopes = new[] { "https://graph.microsoft.com/.default" };

// Values from app registration
var clientId = "YOUR_CLIENT_ID";
var tenantId = "YOUR_TENANT_ID";
var clientSecret = "YOUR_CLIENT_SECRET";

// using Azure.Identity;
var options = new ClientSecretCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
};

// https://learn.microsoft.com/dotnet/api/azure.identity.clientsecretcredential
var clientSecretCredential = new ClientSecretCredential(
    tenantId, clientId, clientSecret, options);

var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
© www.soinside.com 2019 - 2024. All rights reserved.