共用方式為


快速入門:使用主控台應用程式的身分識別取得權杖並呼叫 Microsoft Graph API

歡迎! 這可能不是您預期的頁面。 當我們處理修正程式時,此連結應會將您導向至正確的文章:

快速入門:取得權杖,並在 .NET 主控台應用程式呼叫 Microsoft Graph

當我們努力解決問題時,也對您的不便深感抱歉,並感謝您的耐心等候。

下列快速入門會使用程式碼範例,示範 .NET 主控台應用程式如何取得存取權杖來呼叫 Microsoft Graph API,以及顯示目錄中的使用者清單。 也會示範作業或 Windows 服務如何使用應用程式識別來執行,而不是以使用者的身分識別執行。 本快速入門中的範例主控台應用程式也是背景程式應用程式,因此是機密用戶端應用程式。

必要條件

.NET 6.0 SDK 的最低需求。

下載並設定您的快速入門應用程式

步驟 1:在 Azure 入口網站中設定您的應用程式

若要讓本快速入門中的程式碼範例能夠運作,請建立用戶端密碼,並新增圖形 API 的 User.Read.All 應用程式權限。

已設定 您的應用程式會使用這些屬性進行設定。

步驟 2:下載您的 Visual Studio 專案

使用 Visual Studio 2022 執行專案。

提示

為了避免 Windows 中路徑長度限制所造成的錯誤,建議您將封存解壓縮或將存放庫複製到磁碟機根目錄附近的目錄中。

注意

Enter_the_Supported_Account_Info_Here

立即執行應用程式會導致輸出 HTTP 403 - Forbidden* error: "Insufficient privileges to complete the operation。 之所以發生此錯誤,是因為任何僅限應用程式權限都需要目錄的全域管理員對應用程式表示同意。 視角色而定,選取下列其中一個選項。

全域租用戶管理員

針對全域租用戶系統管理員,請移至 [API 權限] 頁面,選取 [代表 Enter_the_Tenant_Name_Here 授與管理員同意]

標準使用者

如果您是租用戶的標準使用者,則請全域管理員將管理員同意授與給該應用程式。 若要這樣做,請將下列 URL 提供給系統管理員:

https://login.microsoftonline.com/Enter_the_Tenant_Id_Here/adminconsent?client_id=Enter_the_Application_Id_Here

當您使用上述 URL 向應用程式授與同意之後,可能會顯示此錯誤 AADSTS50011: No reply address is registered for the application。 發生此錯誤的原因是此應用程式和 URL 都沒有重新導向 URI。 請不用理會這一則訊息。

步驟 4:執行應用程式

在 Visual Studio 中,按 F5 鍵以執行應用程式。 否則,請透過命令提示字元、主控台或終端機來執行應用程式:

cd {ProjectFolder}\1-Call-MSGraph\daemon-console
dotnet run

在該程式碼中:

  • {ProjectFolder} 是 .zip 檔案解壓縮所在的資料夾。 例如 C:\Azure-Samples\active-directory-dotnetcore-daemon-v2

結果應該會顯示 Microsoft Entra ID 中的使用者清單。

此快速入門應用程式會使用用戶端秘密,將自己識別為機密用戶端。 用戶端密碼會以純文字的形式新增至專案檔。 基於安全性考量,建議您在將應用程式視為實際執行應用程式之前,先使用憑證而不是用戶端密碼。 如需如何使用憑證的詳細資訊,請參閱這些指示 \(部分機器翻譯\)。

其他相關資訊

本節會概述登入使用者所需的程式碼。 本概觀有助於了解 > 程式碼的運作方式、主要引數為何,以及如何將登入新增至現有的 .NET 主控台應用程式。

此範例的運作方式

此圖顯示本快速入門所產生範例應用程式的運作方式。

Microsoft.Identity.Web.GraphServiceClient

Microsoft Identity Web (在 Microsoft.Identity.Web.TokenAcquisition 套件中) 是用來要求權杖的程式庫,以存取受 Microsoft 身分識別平台保護的 API。 本快速入門會使用應用程式本身的身分識別 (而非委派的權限) 來要求權杖。 此案例所使用的驗證流程稱為用戶端認證 OAuth 流程。 如需如何搭配使用 MSAL.NET 與用戶端認證流程的詳細資訊,請參閱這篇文章。 鑑於本快速入門中的精靈應用程式會呼叫 Microsoft Graph,您可以安裝 Microsoft.Identity.Web.GraphServiceClient 套件,此套件會自動處理 Microsoft Graph 的已驗證要求 (並自行參考 Microsoft.Identity.Web.TokenAcquisition)

您可以在 Visual Studio 套件管理員主控台中執行下列命令,以安裝 Microsoft.Identity.Web.GraphServiceClient:

dotnet add package Microsoft.Identity.Web.GraphServiceClient

應用程式初始化

透過新增下列程式碼來新增 Microsoft.Identity.Web 的參考:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Graph;
using Microsoft.Identity.Abstractions;
using Microsoft.Identity.Web;

然後,使用下列命令初始化應用程式:

// Get the Token acquirer factory instance. By default it reads an appsettings.json
// file if it exists in the same folder as the app (make sure that the 
// "Copy to Output Directory" property of the appsettings.json file is "Copy if newer").
TokenAcquirerFactory tokenAcquirerFactory = TokenAcquirerFactory.GetDefaultInstance();

// Configure the application options to be read from the configuration
// and add the services you need (Graph, token cache)
IServiceCollection services = tokenAcquirerFactory.Services;
services.AddMicrosoftGraph();
// By default, you get an in-memory token cache.
// For more token cache serialization options, see https://aka.ms/msal-net-token-cache-serialization

// Resolve the dependency injection.
var serviceProvider = tokenAcquirerFactory.Build();

此程式碼會使用 appsettings.json 檔案中定義的組態:

{
   "AzureAd": {
       "Instance": "https://login.microsoftonline.com/",
       "TenantId": "[Enter here the tenantID or domain name for your Azure AD tenant]",
       "ClientId": "[Enter here the ClientId for your application]",
       "ClientCredentials": [
           {
              "SourceType": "ClientSecret",
              "ClientSecret": "[Enter here a client secret for your application]"
           }
       ]
   }
}
元素 描述
ClientSecret 在 Azure 入口網站中為應用程式建立的用戶端密碼。
ClientId 註冊於 Azure 入口網站中的應用程式所具備的應用程式 (用戶端) 識別碼。 您可以在 Azure 入口網站的應用程式 [概觀] 頁面中找到此值。
Instance (選用) 應用程式進行驗證的 Security Token Service (STS) 雲端執行個體端點。 這通常是用於公用雲端的 https://login.microsoftonline.com/
TenantId 租用戶的名稱或租用戶識別碼。

如需詳細資訊,請參閱 ConfidentialClientApplication 的參考文件

呼叫 Microsoft Graph

若要使用應用程式的身分識別來要求權杖,請使用 AcquireTokenForClient 方法:

GraphServiceClient graphServiceClient = serviceProvider.GetRequiredService<GraphServiceClient>();
var users = await graphServiceClient.Users
              .GetAsync(r => r.Options.WithAppOnly());

說明與支援 

如果您需要協助、想要回報問題,或想要深入了解您的支援選項,請參閱 開發人員的協助與支援

下一步

若要深入了解精靈應用程式,請參閱案例概觀: