调用 Web API 的桌面应用:代码配置

创建应用程序以后,即可了解如何使用应用程序的坐标来配置代码。

支持桌面应用的 Microsoft 库

以下 Microsoft 库支持桌面应用:

语言/框架 项目
GitHub
获取
started
用户登录 访问 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 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.AzureChina,
                         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.cn/tfp/{tenant}/{PolicySignInSignUp}")
        .Build();

了解详细信息

若要详细了解如何配置 MSAL.NET 桌面应用程序,请执行以下操作:

包含配置选项的完整示例

假设有一个 .NET 控制台应用程序,其中包含以下 appsettings.json 配置文件:

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

  "WebAPI": {
    "MicrosoftGraphBaseEndpoint": "https://microsoftgraph.chinacloudapi.cn"
  }
}

使用 .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 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 方法来重写配置,如前所示。

后续步骤

转到此方案中的下一篇文章:获取桌面应用的令牌