MSAL을 이용한 Microsoft Graph 인증

Graph 인증 소개

Microsoft Graph Outlook, OneDrive, Teams 등 Microsoft 365 서비스 전반의 데이터를 액세스하기 위한 통합 REST API입니다. 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 서비스에 인증된 요청을 보내기 위해.

Microsoft 인증 라이브러리 (MSAL)

단계 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 인스턴스. Microsoft Graph와 상호 작용을 시작하려면 리소스 유형과 ID를 설정하십시오.

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. The 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";