Autentikasi Microsoft Graph dengan MSAL
Pendahuluan tentang Autentikasi Graph
Microsoft Graph adalah API REST terpadu untuk mengakses data di seluruh layanan Microsoft 365 seperti Outlook, OneDrive, dan Teams. Aspose.Email untuk .NET menyediakan IGraphClient antarmuka yang menyederhanakan interaksi dengan Microsoft Graph dengan menawarkan API tingkat tinggi yang strongly-typed.
Menggunakan IGraphClient, Anda dapat mengautentikasi via MSAL, lalu melakukan operasi umum seperti:
-
Mengelola folder surat (daftar, buat, perbarui, salin, hapus)
-
Bekerja dengan pesan dan lampiran (membaca, mengirim, memindahkan, dan memanipulasi konten)
-
Mengakses dan mengelola acara kalender, kontak, kategori, aturan, tugas, dan notebook OneNote
Contoh berikut menunjukkan cara membuat dan mengkonfigurasi sebuah GraphClient instance dengan token akses, diikuti dengan skenario penggunaan umum.
Autentikasi Microsoft Graph dengan MSAL.NET
Untuk bekerja dengan Microsoft Graph menggunakan Aspose.Email untuk .NET, Anda harus terlebih dahulu mengautentikasi aplikasi Anda. Hal ini dapat dilakukan dengan mengimplementasikan ITokenProvider antarmuka, yang menyediakan token akses ke IGraphClient.
Bagian ini memandu Anda dalam menyiapkan MSAL.NET untuk memperoleh token dan menginisialisasi IGraphClient untuk mengirim permintaan terautentikasi ke layanan Microsoft Graph.
Microsoft Authentication Library (MSAL)
Langkah 1: Definisikan Kelas AccessParameters
Buat kelas sederhana untuk menyimpan kredensial Microsoft 365 Anda dan konfigurasi terkait.
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";
}
Langkah 2: Pasang Paket MSAL.NET
Tambahkan Microsoft.Identity.Client Paket NuGet ke proyek Anda. Paket ini berisi Microsoft Authentication Library (MSAL) yang digunakan untuk memperoleh token akses.
dotnet add package Microsoft.Identity.Client
Langkah 3: Implementasikan Interface ITokenProvider
Buat sebuah GraphTokenProvider kelas yang mengimplementasikan ITokenProvider antarmuka. Kelas ini akan menggunakan pustaka MSAL.NET untuk memperoleh token akses.
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;
}
Langkah 4: Buat Instance ITokenProvider
Setelah Anda GraphTokenProvider kelas siap, Anda dapat menginstansinya menggunakan kredensial aplikasi Anda.
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);
Langkah 5: Inisialisasi IGraphClient
Gunakan penyedia token untuk membuat IGraphClient instance. Atur tipe sumber daya dan ID untuk mulai berinteraksi dengan Microsoft Graph.
using var client = GraphClient.GetClient(tokenProvider, accessParams.TenantId);
client.Resource = ResourceType.Users;
client.ResourceId = accessParams.UserId;
IGraphClient Anda kini terautentikasi dan siap mengirim permintaan ke Microsoft Graph atas nama aplikasi Anda.
Terhubung ke Endpoint GCC High di Microsoft Graph
Aspose.Email GraphClient mendukung koneksi ke endpoint Microsoft Graph GCC High dengan mengatur EndPoint properti secara manual. Atur properti menjadi https://graph.microsoft.us sebelum membuat permintaan.
Contoh kode berikut menunjukkan cara mengkonfigurasi GraphClient untuk terhubung ke endpoint GCC High untuk daftar folder dan mengambil pesan.
client.EndPoint = "https://graph.microsoft.us";
var folders = client.ListFolders();
string folderId = folders.Find(x => x.DisplayName == "Inbox").ItemId;
var msgs = client.ListMessages(folderId);
Autentikasi Asynchronous ke Microsoft Graph
Gunakan Aspose.Email.Clients.Graph.IGraphClientAsync antarmuka untuk melakukan operasi asynchronous dengan GraphClient. The GraphClient.GetClientAsync(ITokenProvider, string) dan GraphClient.GetClientAsync(IMultipleServicesTokenProvider, string) metode memungkinkan Anda untuk menginisialisasi klien Graph asynchronous. Contoh kode berikut menunjukkan cara mengkonfigurasi klien Microsoft Graph yang terautentikasi dengan kredensial aplikasi Azure AD sehingga dapat beroperasi pada kotak surat pengguna tertentu:
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";