การตรวจสอบสิทธิ์ Microsoft Graph ด้วย MSAL

แนะนำการตรวจสอบสิทธิ์ Graph

Microsoft Graph เป็น REST API ที่รวมศูนย์สำหรับเข้าถึงข้อมูลในบริการ Microsoft 365 เช่น Outlook, OneDrive, และ Teams. Aspose.Email for .NET มีในตัว IGraphClient อินเทอร์เฟซที่ทำให้การโต้ตอบกับ Microsoft Graph ง่ายขึ้นโดยให้ API ระดับสูงแบบ strongly-typed.

โดยใช้ IGraphClient, คุณสามารถตรวจสอบสิทธิ์ผ่าน MSAL แล้วทำปฏิบัติการทั่วไปเช่น:

  • จัดการโฟลเดอร์เมล (แสดงรายการ, สร้าง, อัปเดต, คัดลอก, ลบ)

  • ทำงานกับข้อความและไฟล์แนบ (อ่าน, ส่ง, ย้าย, และจัดการเนื้อหา)

  • การเข้าถึงและจัดการเหตุการณ์ปฏิทิน, รายชื่อผู้ติดต่อ, หมวดหมู่, กฎ, งาน, และโน้ตบุ๊ก OneNote

ตัวอย่างต่อไปนี้แสดงวิธีสร้างและกำหนดค่า GraphClient อินสแตนซ์พร้อม access token ตามด้วยสถานการณ์การใช้งานทั่วไป.

ตรวจสอบสิทธิ์ Microsoft Graph ด้วย MSAL.NET

เพื่อทำงานกับ Microsoft Graph โดยใช้ Aspose.Email for .NET คุณต้องตรวจสอบสิทธิ์แอปของคุณก่อน ซึ่งทำได้โดยการ Implement ITokenProvider อินเทอร์เฟซ ซึ่งให้ access token แก่ IGraphClient.

ส่วนนี้จะแนะนำคุณผ่านการตั้งค่า MSAL.NET เพื่อรับ token และการเริ่มต้น IGraphClient เพื่อส่งคำขอที่ผ่านการตรวจสอบสิทธิ์ไปยังบริการ Microsoft Graph.

Microsoft Authentication Library (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) ที่ใช้เพื่อรับ access token.

dotnet add package Microsoft.Identity.Client

ขั้นตอนที่ 3: Implement อินเทอร์เฟซ ITokenProvider

สร้าง GraphTokenProvider คลาสที่ทำการใช้งาน ITokenProvider interface. คลาสนี้จะใช้ไลบรารี 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

ใช้ตัวจัดหาตoken เพื่อสร้าง IGraphClient อินสแตนซ์ ตั้งประเภทและ ID ของทรัพยากรเพื่อเริ่มโต้ตอบกับ Microsoft Graph.

using var client = GraphClient.GetClient(tokenProvider, accessParams.TenantId);

client.Resource = ResourceType.Users;
client.ResourceId = accessParams.UserId;

IGraphClient ของคุณได้รับการตรวจสอบสิทธิ์แล้วและพร้อมส่งคำขอไปยัง Microsoft Graph ในนามของแอปพลิเคชันของคุณ.

เชื่อมต่อกับเอ็นด์พอยต์ GCC High ใน Microsoft Graph

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 แบบอะซิงโครนัส ตัวอย่างโค้ดด้านล่างแสดงวิธีกำหนดค่าคลไอเอนท์ Microsoft Graph ที่ผ่านการตรวจสอบสิทธิ์ด้วยข้อมูลรับรองแอปพลิเคชัน Azure AD เพื่อให้สามารถทำงานกับกล่องจดหมายของผู้ใช้คนใดคนหนึ่งได้:

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