Aplikasi desktop yang memanggil API web: Mendapatkan token menggunakan autentikasi Windows terintegrasi

Untuk memasukkan pengguna domain di domain atau komputer yang bergabung dengan Microsoft Entra, gunakan autentikasi Windows terintegrasi (IWA).

Kendala

  • Autentikasi Windows terintegrasi hanya tersedia untuk pengguna federasi+ , yaitu, pengguna yang dibuat di Direktori Aktif dan didukung oleh ID Microsoft Entra. Pengguna yang dibuat langsung di MICROSOFT Entra ID tanpa dukungan Direktori Aktif, yang dikenal sebagai pengguna terkelola , tidak dapat menggunakan alur autentikasi ini. Batasan ini tidak memengaruhi alur nama pengguna dan kata sandi.

  • IWA tidak melewati autentikasi multifaktor (MFA). Jika MFA dikonfigurasi, IWA mungkin gagal jika tantangan MFA diperlukan, karena MFA memerlukan interaksi pengguna.

    IWA tidak interaktif, tetapi MFA membutuhkan interaktivitas pengguna. Anda tidak mengontrol kapan penyedia identitas meminta MFA untuk dilakukan, admin penyewa yang melakukannya. Dari pengamatan kami, MFA diperlukan ketika Anda masuk dari negara/wilayah yang berbeda, ketika tidak terhubung melalui VPN ke jaringan perusahaan, dan kadang-kadang bahkan ketika terhubung melalui VPN. Jangan berharap seperangkat aturan yang menentukan. MICROSOFT Entra ID menggunakan AI untuk terus mempelajari apakah MFA diperlukan. Kembali ke prompt pengguna seperti autentikasi interaktif atau aliran kode perangkat jika IWA gagal.

  • Kewenangan yang disahkan pada PublicClientApplicationBuilder perlu:

    • Penyewa dalam formulir https://login.microsoftonline.com/{tenant}/, di manatenant GUID mewakili ID penyewa atau nama domain yang terkait dengan penyewa.
    • Untuk setiap akun kantor dan sekolah: https://login.microsoftonline.com/organizations/.
    • Akun pribadi Microsoft tidak didukung. Anda tidak dapat menggunakan penyewa /common atau /consumers.
  • Karena autentikasi Windows terintegrasi adalah aliran senyap:

    • Pengguna aplikasi Anda sebelumnya harus setuju untuk menggunakan aplikasi.
    • Admin penyewa sebelumnya harus telah menyetujui semua pengguna dalam penyewa untuk menggunakan aplikasi.
    • Dengan kata lain:
      • Baik Anda sebagai pengembang memilih tombol Grant di portal Microsoft Azure untuk Anda sendiri.
      • Atau, admin penyewa memilih tombol Berikan/cabut persetujuan admin untuk {tenant domain} pada tab izin akses API pendaftaran untuk aplikasi. Untuk informasi selengkapnya, lihat Menambahkan izin untuk mengakses API web Anda.
      • Atau, Anda telah menyediakan cara bagi pengguna untuk menyetujui aplikasi. Untuk informasi selengkapnya, lihat Meminta persetujuan pengguna individual.
      • Atau, Anda telah menyediakan cara bagi admin penyewa untuk menyetujui aplikasi. Untuk informasi selengkapnya, lihat Persetujuan admin.
  • Alur ini diaktifkan untuk aplikasi .NET desktop, .NET, dan UWP.

Untuk informasi selengkapnya pada persetujuan, lihat Izin dan persetujuan di platform identitas Microsoft.

Pelajari cara menggunakannya

Pada MSAL.NET, gunakan:

AcquireTokenByIntegratedWindowsAuth(IEnumerable<string> scopes)

Anda biasanya hanya membutuhkan satu parameter (scopes). Bergantung pada cara administrator Windows Anda menyetel kebijakan, aplikasi pada mesin Windows Anda mungkin tidak diperbolehkan mencari pengguna yang masuk. Dalam hal ini, gunakan metode kedua, .WithUsername(), dan berikan nama pengguna dari pengguna yang masuk sebagai format UPN, misalnya, joe@contoso.com.

Contoh berikut menyajikan kasus terbaru, dengan penjelasan tentang jenis pengecualian yang bisa Anda dapatkan dan mitigasinya.

static async Task GetATokenForGraph()
{
 string authority = "https://login.microsoftonline.com/contoso.com";
 string[] scopes = new string[] { "user.read" };
 IPublicClientApplication app = PublicClientApplicationBuilder
      .Create(clientId)
      .WithAuthority(authority)
      .Build();

 var accounts = await app.GetAccountsAsync();

 AuthenticationResult result = null;
 if (accounts.Any())
 {
  result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
      .ExecuteAsync();
 }
 else
 {
  try
  {
   result = await app.AcquireTokenByIntegratedWindowsAuth(scopes)
      .ExecuteAsync(CancellationToken.None);
  }
  catch (MsalUiRequiredException ex)
  {
   // MsalUiRequiredException: AADSTS65001: The user or administrator has not consented to use the application
   // with ID '{appId}' named '{appName}'.Send an interactive authorization request for this user and resource.

   // you need to get user consent first. This can be done, if you are not using .NET (which does not have any Web UI)
   // by doing (once only) an AcquireToken interactive.

   // If you are using .NET or don't want to do an AcquireTokenInteractive, you might want to suggest the user to navigate
   // to a URL to consent: https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id={clientId}&response_type=code&scope=user.read

   // AADSTS50079: The user is required to use multi-factor authentication.
   // There is no mitigation - if MFA is configured for your tenant and AAD decides to enforce it,
   // you need to fallback to an interactive flows such as AcquireTokenInteractive or AcquireTokenByDeviceCode
   }
   catch (MsalServiceException ex)
   {
    // Kind of errors you could have (in ex.Message)

    // MsalServiceException: AADSTS90010: The grant type is not supported over the /common or /consumers endpoints. Please use the /organizations or tenant-specific endpoint.
    // you used common.
    // Mitigation: as explained in the message from Azure AD, the authority needs to be tenanted or otherwise organizations

    // MsalServiceException: AADSTS70002: The request body must contain the following parameter: 'client_secret or client_assertion'.
    // Explanation: this can happen if your application was not registered as a public client application in Azure AD
    // Mitigation: in the Azure portal, edit the manifest for your application and set the `allowPublicClient` to `true`
   }
   catch (MsalClientException ex)
   {
      // Error Code: unknown_user Message: Could not identify logged in user
      // Explanation: the library was unable to query the current Windows logged-in user or this user is not AD or AAD
      // joined (work-place joined users are not supported).

      // Mitigation 1: on UWP, check that the application has the following capabilities: Enterprise Authentication,
      // Private Networks (Client and Server), User Account Information

      // Mitigation 2: Implement your own logic to fetch the username (e.g. john@contoso.com) and use the
      // AcquireTokenByIntegratedWindowsAuth form that takes in the username

      // Error Code: integrated_windows_auth_not_supported_managed_user
      // Explanation: This method relies on a protocol exposed by Active Directory (AD). If a user was created in Azure
      // Active Directory without AD backing ("managed" user), this method will fail. Users created in AD and backed by
      // AAD ("federated" users) can benefit from this non-interactive method of authentication.
      // Mitigation: Use interactive authentication
   }
 }

 Console.WriteLine(result.Account.Username);
}

Untuk daftar kemungkinan pengubah pada AcquireTokenByIntegratedWindowsAuthentication, lihat AcquireTokenByIntegratedWindowsAuthParameterBuilder.

Langkah berikutnya

Lanjutkan ke artikel berikutnya dalam skenario ini, yaitu Panggil API web dari aplikasi desktop.