通过 MSAL.NET 使用配置选项实例化公共客户端应用程序Instantiate a public client application with configuration options using MSAL.NET

本文介绍如何使用适用于 .NET 的 Microsoft 身份验证库 (MSAL.NET) 实例化公共客户端应用程序This article describes how to instantiate a public client application using Microsoft Authentication Library for .NET (MSAL.NET). 应用程序使用设置文件中定义的配置选项进行实例化。The application is instantiated with configuration options defined in a settings file.

在初始化应用程序之前,首先需要注册它,以便应用可以与 Microsoft 标识平台集成。Before initializing an application, you first need to register it so that your app can be integrated with the Microsoft identity platform. 注册后,可能需要以下信息(可在 Azure 门户中找到):After registration, you may need the following information (which can be found in the Azure portal):

  • 客户端 ID(表示 GUID 的字符串)The client ID (a string representing a GUID)
  • 标识提供者 URL(命名了实例)和应用程序的登录受众。The identity provider URL (named the instance) and the sign-in audience for your application. 这两个参数统称为颁发机构。These two parameters are collectively known as the authority.
  • 如果你仅在为组织编写业务线应用程序(也称为单租户应用程序),则为租户 ID。The tenant ID if you are writing a line of business application solely for your organization (also named single-tenant application).
  • 对于 Web 应用,有时对于公共客户端应用(特别是当你的应用需要使用中转站时),还将需要设置 redirectUri,标识提供者将在其中使用安全令牌联系你的应用程序。For web apps, and sometimes for public client apps (in particular when your app needs to use a broker), you'll have also set the redirectUri where the identity provider will contact back your application with the security tokens.

.NET Core 控制台应用程序可以具有以下 appsettings.json 配置文件:A .NET Core console application could have the following appsettings.json configuration file:

{
  "Authentication": {
    "AzureCloudInstance": "AzureChina",
    "AadAuthorityAudience": "AzureAdMultipleOrgs",
    "ClientId": "ebe2ab4d-12b3-4446-8480-5c3828d04c50"
  },

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

以下代码使用 .NET 配置框架读取此文件:The following code reads this file using the .NET configuration framework:

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 is ran
    /// in Azure public clouds or national / 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 config
        SampleConfiguration config = new SampleConfiguration()
        {
            PublicClientApplicationOptions = new PublicClientApplicationOptions()
        };
        Configuration.Bind("Authentication", config.PublicClientApplicationOptions);
        config.MicrosoftGraphBaseEndpoint = Configuration.GetValue<string>("WebAPI:MicrosoftGraphBaseEndpoint");
        return config;
    }
}

以下代码使用设置文件中的配置创建应用程序:The following code creates your application, using the configuration from the settings file:

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