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

本文介绍如何使用适用于 .NET 的 Microsoft 身份验证库 (MSAL.NET) 实例化机密客户端应用程序This article describes how to instantiate a confidential 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).
  • 应用程序机密(客户端机密字符串);对于机密客户端应用,需要获取证书(类型为 X509Certificate2)。The application secret (client secret string) or certificate (of type X509Certificate2) if it's a confidential client app.
  • 对于 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.

根据配置文件配置应用程序Configure the application from the config file

MSAL.NET 中选项的属性名称与 ASP.NET Core 中 AzureADOptions 的属性名称匹配,因此不需编写任何粘附代码。The name of the properties of the options in MSAL.NET match the name of the properties of the AzureADOptions in ASP.NET Core, so you don't need to write any glue code.

appsettings.json 文件中介绍了 ASP.NET Core 应用程序配置:An ASP.NET Core application configuration is described in an appsettings.json file:

{
  "AzureAd": {
    "Instance": "https://login.partner.microsoftonline.cn/",
    "Domain": "[Enter the domain of your tenant, e.g. contoso.partner.onmschina.cn]",
    "TenantId": "[Enter 'common', or 'organizations' or the Tenant Id (Obtained from the Azure portal. Select 'Endpoints' from the 'App registrations' blade and use the GUID in any of the URLs), e.g. da41245a5-11b3-996c-00a8-4d99re19f292]",
    "ClientId": "[Enter the Client Id (Application ID obtained from the Azure portal), e.g. ba74781c2-53c2-442a-97c2-3d60re42f403]",
    "CallbackPath": "/signin-oidc",
    "SignedOutCallbackPath ": "/signout-callback-oidc",

    "ClientSecret": "[Copy the client secret added to the app from the Azure portal]"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

从 MSAL.NET v3.x 开始,可以根据配置文件配置机密客户端应用程序。Starting in MSAL.NET v3.x, you can configure your confidential client application from the config file.

在需要配置和实例化应用程序的类中,需声明 ConfidentialClientApplicationOptions 对象。In the class where you want configure and instantiate your application, you need to declare a ConfidentialClientApplicationOptions object. 使用 Microsoft.Extensions.Configuration.Binder nuget 包 中的 IConfigurationRoot.Bind() 方法,将从源读取的配置(包括 appconfig.json 文件)绑定到应用程序选项的实例:Bind the configuration read from the source (including the appconfig.json file) to the instance of the application options, using the IConfigurationRoot.Bind() method from the Microsoft.Extensions.Configuration.Binder nuget package:

using Microsoft.Identity.Client;

private ConfidentialClientApplicationOptions _applicationOptions;
_applicationOptions = new ConfidentialClientApplicationOptions();
configuration.Bind("AzureAD", _applicationOptions);

这样就可以将 appsettings.json 文件“AzureAD”节的内容绑定到 ConfidentialClientApplicationOptions 对象的相应属性。This enables the content of the "AzureAD" section of the appsettings.json file to be bound to the corresponding properties of the ConfidentialClientApplicationOptions object. 接下来,构建 ConfidentialClientApplication 对象:Next, build a ConfidentialClientApplication object:

IConfidentialClientApplication app;
app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(_applicationOptions)
        .Build();

添加运行时配置Add runtime configuration

在机密客户端应用程序中,通常会为每个用户设置一个缓存。In a confidential client application, you usually have a cache per user. 因此,需将缓存关联到用户,并告知应用程序生成器你需要使用它。Therefore you will need to get the cache associated with the user and inform the application builder that you want to use it. 同样,你可以有一个动态计算的重定向 URI。In the same way, you might have a dynamically computed redirect URI. 在此示例中,代码如下:In this case the code is the following:

IConfidentialClientApplication app;
var request = httpContext.Request;
var currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, _azureAdOptions.CallbackPath ?? string.Empty);
app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(_applicationOptions)
       .WithRedirectUri(currentUri)
       .Build();
TokenCache userTokenCache = _tokenCacheProvider.SerializeCache(app.UserTokenCache,httpContext, claimsPrincipal);