呼叫 Web API 的桌面應用程式:程式代碼設定

現在您已建立應用程式,您將瞭解如何使用應用程式的座標來設定程序代碼。

支援傳統型應用程式的 Microsoft 連結庫

下列 Microsoft 連結庫支援傳統型應用程式:

語言/ 架構 項目開啟
GitHub
套件 取得
啟動
登入使用者 存取 Web API 正式推出 (GA)
公開預覽1
Electron MSAL Node.js msal-node Library can request ID tokens for user sign-in. Library can request access tokens for protected web APIs. 公開預覽
Java MSAL4J msal4j Library can request ID tokens for user sign-in. Library can request access tokens for protected web APIs. GA
macOS (Swift/Obj-C) 適用於 iOS 和 macOS 的 MSAL MSAL 教學課程 Library can request ID tokens for user sign-in. Library can request access tokens for protected web APIs. GA
UWP MSAL.NET Microsoft.Identity.Client 教學課程 Library can request ID tokens for user sign-in. Library can request access tokens for protected web APIs. GA
WPF MSAL.NET Microsoft.Identity.Client 教學課程 Library can request ID tokens for user sign-in. Library can request access tokens for protected web APIs. GA

1在線服務的通用授權條款適用於公開預覽中的連結庫。

公用用戶端應用程式

從程式代碼的觀點來看,傳統型應用程式是公用用戶端應用程式。 不論您是否使用互動式驗證,組態會稍有不同。

您必須建置及操作 MSAL.NET IPublicClientApplication

IPublicClientApplication

依程式代碼獨佔

下列程式代碼會具現化公用用戶端應用程式,並使用公司或學校帳戶或個人 Microsoft 帳戶登入 Microsoft Azure 公用雲端中的使用者。

IPublicClientApplication app = PublicClientApplicationBuilder.Create(clientId)
    .Build();

如果您想要使用互動式驗證或裝置程式代碼流程,如先前所示,請使用 .WithRedirectUri 修飾詞。

IPublicClientApplication app;
app = PublicClientApplicationBuilder.Create(clientId)
        .WithDefaultRedirectUri()
        .Build();

使用組態檔

下列程式代碼會從組態物件具現化公用用戶端應用程式,以程式設計方式填入或從組態檔讀取。

PublicClientApplicationOptions options = GetOptions(); // your own method
IPublicClientApplication app = PublicClientApplicationBuilder.CreateWithApplicationOptions(options)
        .WithDefaultRedirectUri()
        .Build();

更細緻的組態

您可以藉由新增一些修飾詞來詳細說明應用程式建置。 例如,如果您想要讓應用程式成為國家雲端中的多租使用者應用程式,例如這裡顯示的美國政府,您可以撰寫:

IPublicClientApplication app;
app = PublicClientApplicationBuilder.Create(clientId)
        .WithDefaultRedirectUri()
        .WithAadAuthority(AzureCloudInstance.AzureUsGovernment,
                         AadAuthorityAudience.AzureAdMultipleOrgs)
        .Build();

MSAL.NET 也包含 Active Directory 同盟服務 2019 的修飾詞:

IPublicClientApplication app;
app = PublicClientApplicationBuilder.Create(clientId)
        .WithAdfsAuthority("https://consoso.com/adfs")
        .Build();

最後,如果您想要取得 Azure Active Directory (Azure AD) B2C 租使用者的令牌,請指定您的租使用者,如下列代碼段所示:

IPublicClientApplication app;
app = PublicClientApplicationBuilder.Create(clientId)
        .WithB2CAuthority("https://fabrikamb2c.b2clogin.com/tfp/{tenant}/{PolicySignInSignUp}")
        .Build();

深入了解

若要深入瞭解如何設定 MSAL.NET 傳統型應用程式:

使用組態選項的完整範例

想像一下具有下列 appsettings.json 組態檔的 .NET 控制台應用程式:

{
  "Authentication": {
    "AzureCloudInstance": "AzurePublic",
    "AadAuthorityAudience": "AzureAdMultipleOrgs",
    "ClientId": "00001111-aaaa-2222-bbbb-3333cccc4444"
  },

  "WebAPI": {
    "MicrosoftGraphBaseEndpoint": "https://graph.microsoft.com"
  }
}

您可以使用 ,在此檔案中讀取的程式代碼很少。NET 提供的組態架構:

public class SampleConfiguration
{
 /// <summary>
 /// Authentication options
 /// </summary>
 public PublicClientApplicationOptions PublicClientApplicationOptions { get; set; }

 /// <summary>
 /// Base URL for Microsoft Graph (it varies depending on whether the application runs
 /// in Microsoft Azure public clouds or national or sovereign clouds)
 /// </summary>
 public string MicrosoftGraphBaseEndpoint { get; set; }

 /// <summary>
 /// Reads the configuration from a JSON file
 /// </summary>
 /// <param name="path">Path to the configuration json file</param>
 /// <returns>SampleConfiguration as read from the json file</returns>
 public static SampleConfiguration ReadFromJsonFile(string path)
 {
  // .NET configuration
  IConfigurationRoot Configuration;
  var builder = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile(path);
  Configuration = builder.Build();

  // Read the auth and graph endpoint configuration
  SampleConfiguration config = new SampleConfiguration()
  {
   PublicClientApplicationOptions = new PublicClientApplicationOptions()
  };
  Configuration.Bind("Authentication", config.PublicClientApplicationOptions);
  config.MicrosoftGraphBaseEndpoint =
  Configuration.GetValue<string>("WebAPI:MicrosoftGraphBaseEndpoint");
  return config;
 }
}

現在,若要建立您的應用程式,請撰寫下列程序代碼:

SampleConfiguration config = SampleConfiguration.ReadFromJsonFile("appsettings.json");
var app = PublicClientApplicationBuilder.CreateWithApplicationOptions(config.PublicClientApplicationOptions)
           .WithDefaultRedirectUri()
           .Build();

在呼叫 .Build() 方法之前,您可以使用對 方法的呼叫 .WithXXX 來覆寫組態,如先前所示。

下一步

請移至此案例中的下一篇文章, 取得傳統型應用程式的令牌。