创建 Microsoft Graph 客户端

Microsoft Graph 客户端用于简化呼叫 Microsoft Graph 的操作。 应用程序的生命周期内,仅需使用一个客户端实例。 有关如何在项目中添加和安装 Microsoft Graph 客户端包的信息,请参阅 安装 SDK

以下代码示例说明了如何通过身份验证认证器以支持语言创建 Microsoft Graph 客户端示例。 身份验证认证器将负责获取应用程序的访问令牌。 每种语言和平台都有多个不同的身份验证认证器可用。 不同的身份验证提供程序支持不同的客户端方案。 有关认证器和选项适用场景的详细信息,请参阅 选择身份验证认证器

var scopes = new[] { "User.Read" };

// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "common";

// Value from app registration
var clientId = "YOUR_CLIENT_ID";

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

// Callback function that receives the user prompt
// Prompt contains the generated device code that you must
// enter during the auth process in the browser
Func<DeviceCodeInfo, CancellationToken, Task> callback = (code, cancellation) => {
    Console.WriteLine(code.Message);
    return Task.FromResult(0);
};

// https://learn.microsoft.com/dotnet/api/azure.identity.devicecodecredential
var deviceCodeCredential = new DeviceCodeCredential(
    callback, tenantId, clientId, options);

var graphClient = new GraphServiceClient(deviceCodeCredential, scopes);