使用 MSAL 的 Microsoft Graph 身份验证
Graph 身份验证简介
Microsoft Graph 是一个统一的 REST API,用于访问 Microsoft 365 服务(如 Outlook、OneDrive 和 Teams)中的数据。Aspose.Email for .NET 提供了内置的 IGraphClient 提供高级、强类型 API 的接口,简化了与 Microsoft Graph 的交互。
使用 IGraphClient,您可以通过 MSAL 进行身份验证,然后执行常见操作,例如:
-
管理邮件文件夹(列出、创建、更新、复制、删除)
-
处理消息和附件(读取、发送、移动以及操控内容)
-
访问和管理日历事件、联系人、类别、规则、任务以及 OneNote 笔记本
以下示例演示如何创建和配置一个 GraphClient 使用访问令牌的实例,然后是典型的使用场景。
使用 MSAL.NET 对 Microsoft Graph 进行身份验证
要使用 Aspose.Email for .NET 与 Microsoft Graph 配合工作,您必须首先对应用程序进行身份验证。可以通过实现以下内容来完成: ITokenProvider 接口,为其提供访问令牌 IGraphClient.
本节指导您设置 MSAL.NET 以获取令牌并初始化 IGraphClient 以向 Microsoft Graph 服务发送已认证请求。
步骤 1:定义 AccessParameters 类
创建一个简单的类来存储您的 Microsoft 365 凭据及相关配置。
public class AccessParameters
{
public string TenantId { get; init; }
public string ClientId { get; init; }
public string ClientSecret { get; init; }
public string UserId { get; init; }
public Uri Authority => new ($"https://login.microsoftonline.com/{TenantId}");
public string ApiUrl => "https://graph.microsoft.com/.default";
}
步骤 2:安装 MSAL.NET 包
添加 Microsoft.Identity.Client 将 NuGet 包添加到您的项目中。它包含用于获取访问令牌的 Microsoft Authentication Library(MSAL)。
dotnet add package Microsoft.Identity.Client
步骤 3:实现 ITokenProvider 接口
创建一个 GraphTokenProvider 实现该接口的类 ITokenProvider 接口。此类将使用 MSAL.NET 库来获取访问令牌。
using Microsoft.Identity.Client;
using Microsoft.Identity.Web;
using Aspose.Email.Clients;
public class GraphTokenProvider : ITokenProvider
{
private readonly IConfidentialClientApplication _app;
private readonly string[] _scopes;
private string? _token;
public GraphTokenProvider(AccessParameters accessParams)
{
_app = ConfidentialClientApplicationBuilder.Create(accessParams.ClientId)
.WithClientSecret(accessParams.ClientSecret)
.WithAuthority(accessParams.Authority)
.Build();
_app.AddInMemoryTokenCache();
_scopes = new[] { accessParams.ApiUrl };
}
public void Dispose()
{
throw new NotImplementedException();
}
public OAuthToken GetAccessToken()
{
return GetAccessToken(false);
}
public OAuthToken GetAccessToken(bool ignoreExistingToken)
{
if (!ignoreExistingToken && _token != null)
{
return new OAuthToken(_token);
}
_token = GetAccessTokenAsync().GetAwaiter().GetResult();
return new OAuthToken(_token);
}
private async Task<string?> GetAccessTokenAsync()
{
AuthenticationResult? result;
try
{
result = await _app.AcquireTokenForClient(_scopes)
.ExecuteAsync();
Console.WriteLine("Token acquired");
}
catch (MsalServiceException ex) when (ex.Message.Contains("AADSTS70011"))
{
Console.WriteLine("Scope provided is not supported");
result = null;
}
if (result == null) return null;
_token = result.AccessToken;
return result.AccessToken;
}
步骤 4:创建 ITokenProvider 实例
一旦您的 GraphTokenProvider 类已就绪,您可以使用应用程序凭据实例化它。
var accessParams = new AccessParameters()
{
TenantId = "Your Tenant ID",
ClientId = "Your Client ID",
ClientSecret = "Your Client Secret",
UserId = "User's Object ID"
};
var tokenProvider = new GraphTokenProvider(accessParams);
步骤 5:初始化 IGraphClient
使用令牌提供程序创建已认证的 IGraphClient 实例。设置资源类型和 ID 以开始与 Microsoft Graph 交互。
using var client = GraphClient.GetClient(tokenProvider, accessParams.TenantId);
client.Resource = ResourceType.Users;
client.ResourceId = accessParams.UserId;
您的 IGraphClient 现已认证,可代表您的应用程序向 Microsoft Graph 发送请求。
在 Microsoft Graph 中连接到 GCC High 端点
Aspose.Email GraphClient 通过设置支持连接到 Microsoft Graph GCC High 端点 EndPoint 属性手动。将属性设置为 https://graph.microsoft.us 在发出请求之前。
以下代码示例演示如何配置 GraphClient 以连接到 GCC High 端点以列出文件夹和检索消息。
client.EndPoint = "https://graph.microsoft.us";
var folders = client.ListFolders();
string folderId = folders.Find(x => x.DisplayName == "Inbox").ItemId;
var msgs = client.ListMessages(folderId);
对 Microsoft Graph 的异步身份验证
使用 Aspose.Email.Clients.Graph.IGraphClientAsync 用于执行异步操作的接口 GraphClient。该 GraphClient.GetClientAsync(ITokenProvider, string) 和 GraphClient.GetClientAsync(IMultipleServicesTokenProvider, string) 这些方法允许您初始化异步 Graph 客户端。以下代码示例演示如何使用 Azure AD 应用程序凭据配置已认证的 Microsoft Graph 客户端,以便它能够操作特定用户的邮箱:
var accessParameters = Settings.User1;
var provider = new AzureConfidentialTokenProvider(
accessParameters.TenantId,
accessParameters.ClientId,
accessParameters.ClientSecret);
var client = GraphClient.GetClientAsync(provider, accessParameters.TenantId);
client.Resource = Aspose.Email.Clients.Graph.ResourceType.Users;
client.ResourceId = accessParameters.Username;
client.EndPoint = "https://graph.microsoft.com";