使用 MSAL.NET 初始化客户端应用程序Initialize client applications using MSAL.NET

本文介绍如何使用适用于 .NET 的 Microsoft 身份验证库 (MSAL.NET) 初始化公共客户端和机密客户端应用程序。This article describes initializing public client and confidential client applications using Microsoft Authentication Library for .NET (MSAL.NET). 若要详细了解客户端应用程序类型和应用程序配置选项,请阅读概述To learn more about the client application types and application configuration options, read the overview.

使用 MSAL.NET 3.x 实例化应用程序的建议方式是使用应用程序生成器 PublicClientApplicationBuilderConfidentialClientApplicationBuilderWith MSAL.NET 3.x, the recommended way to instantiate an application is by using the application builders: PublicClientApplicationBuilder and ConfidentialClientApplicationBuilder. 这些生成器提供强大的机制用于通过代码、配置文件甚至两者的混合来配置应用程序。They offer a powerful mechanism to configure the application either from the code, or from a configuration file, or even by mixing both approaches.

先决条件Prerequisites

在初始化应用程序之前,首先需要将其注册,使应用能够与 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.

初始化应用程序的方式Ways to initialize applications

可通过多种不同的方式来实例化客户端应用程序。There are many different ways to instantiate client applications.

通过代码初始化公共客户端应用程序Initializing a public client application from code

以下代码实例化一个公共客户端应用程序,使用工作和学校帐户在 Azure 云中将用户登录。The following code instantiates a public client application, signing-in users in the Azure cloud, with their work and school accounts.

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

通过代码初始化机密客户端应用程序Initializing a confidential client application from code

以下代码以相同的方式实例化一个机密应用程序(位于 https://myapp.chinacloudsites.cn 上的 Web 应用),该应用程序可以使用工作和学校帐户处理 Azure 云中用户的令牌。In the same way, the following code instantiates a confidential application (a Web app located at https://myapp.chinacloudsites.cn) handling tokens from users in the Azure cloud, with their work and school accounts. 标识提供者通过共享客户端机密标识该应用程序:The application is identified with the identity provider by sharing a client secret:

string redirectUri = "https://myapp.chinacloudsites.cn";
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(clientId)
    .WithClientSecret(clientSecret)
    .WithRedirectUri(redirectUri )
    .Build();

你可能已知道,在生产环境中,最好是与 Azure AD 共享证书,而不要使用客户端机密。As you might know, in production, rather than using a client secret, you might want to share with Azure AD a certificate. 根据此要求,代码如下所示:The code would then be the following:

IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(clientId)
    .WithCertificate(certificate)
    .WithRedirectUri(redirectUri )
    .Build();

通过配置选项初始化公共客户端应用程序Initializing a public client application from configuration options

以下代码通过一个配置对象实例化公共客户端应用程序,该对象可以通过编程方式进行填充,也可以从配置文件读取:The following code instantiates a public client application from a configuration object, which could be filled-in programmatically or read from a configuration file:

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

通过配置选项初始化机密客户端应用程序Initializing a confidential client application from configuration options

可对机密客户端应用程序应用上述相同的模式。The same kind of pattern applies to confidential client applications. 还可以使用 .WithXXX 修饰符(此处为证书)添加其他参数。You can also add other parameters using .WithXXX modifiers (here a certificate).

ConfidentialClientApplicationOptions options = GetOptions(); // your own method
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(options)
    .WithCertificate(certificate)
    .Build();

生成器修饰符Builder modifiers

在使用应用程序生成器的代码片段中,可将许多 .With 方法应用为修饰符(例如 .WithCertificate.WithRedirectUri)。In the code snippets using application builders, a number of .With methods can be applied as modifiers (for example, .WithCertificate and .WithRedirectUri).

公共和机密客户端应用程序通用的修饰符Modifiers common to public and confidential client applications

可在公共客户端或机密客户端应用程序生成器中设置的修饰符包括:The modifiers you can set on a public client or confidential client application builder are:

修饰符Modifier 说明Description
.WithAuthority() 7 个重写.WithAuthority() 7 overrides 将应用程序默认颁发机构设置为 Azure AD 颁发机构,有时还可以选择 Azure 云、受众、租户(租户 ID 或域名),或直接提供颁发机构 URI。Sets the application default authority to an Azure AD authority, with the possibility of choosing the Azure Cloud, the audience, the tenant (tenant ID or domain name), or providing directly the authority URI.
.WithAdfsAuthority(string) 将应用程序默认颁发机构设置为 ADFS 颁发机构。Sets the application default authority to be an ADFS authority.
.WithB2CAuthority(string) 将应用程序默认颁发机构设置为 Azure AD B2C 颁发机构。Sets the application default authority to be an Azure AD B2C authority.
.WithClientId(string) 重写客户端 ID。Overrides the client ID.
.WithComponent(string) 使用 MSAL.NET 设置库的名称(出于遥测原因)。Sets the name of the library using MSAL.NET (for telemetry reasons).
.WithDebugLoggingCallback() 调用后,应用程序将调用 Debug.Write,目的只是启用调试跟踪。If called, the application will call Debug.Write simply enabling debugging traces. 有关详细信息,请参阅日志记录See Logging for more information.
.WithExtraQueryParameters(IDictionary<string,string> eqp) 设置要在所有身份验证请求中发送的应用程序级附加查询参数。Set the application level extra query parameters that will be sent in all authentication request. 可在每个令牌获取方法级别重写此值(具有相同的 .WithExtraQueryParameters pattern)。This is overridable at each token acquisition method level (with the same .WithExtraQueryParameters pattern).
.WithHttpClientFactory(IMsalHttpClientFactory httpClientFactory) 启用高级方案(例如对 HTTP 代理进行配置),或者强制 MSAL 使用特定的 HttpClient(例如,在 ASP.NET Core Web 应用/API 中)。Enables advanced scenarios such as configuring for an HTTP proxy, or to force MSAL to use a particular HttpClient (for instance in ASP.NET Core web apps/APIs).
.WithLogging() 调用后,应用程序将结合调试跟踪调用某个回调。If called, the application will call a callback with debugging traces. 有关详细信息,请参阅日志记录See Logging for more information.
.WithRedirectUri(string redirectUri) 重写默认的重定向 URI。Overrides the default redirect URI. 此操作对于公共客户端应用程序中涉及代理的方案非常有用。In the case of public client applications, this will be useful for scenarios involving the broker.
.WithTelemetry(TelemetryCallback telemetryCallback) 设置用于发送遥测数据的委托。Sets the delegate used to send telemetry.
.WithTenantId(string tenantId) 重写租户 ID 或租户说明。Overrides the tenant ID, or the tenant description.

特定于 Xamarin.iOS 应用程序的修饰符Modifiers specific to Xamarin.iOS applications

可在 Xamarin.iOS 上的公共客户端应用程序生成器中设置的修饰符包括:The modifiers you can set on a public client application builder on Xamarin.iOS are:

修饰符Modifier 说明Description
.WithIosKeychainSecurityGroup() 仅限 Xamarin.iOS:设置 iOS 密钥链安全组(为实现缓存持久性)。Xamarin.iOS only: Sets the iOS key chain security group (for the cache persistence).

特定于机密客户端应用程序的修饰符Modifiers specific to confidential client applications

可在机密客户端应用程序生成器中设置的修饰符包括:The modifiers you can set on a confidential client application builder are:

修饰符Modifier 说明Description
.WithCertificate(X509Certificate2 certificate) 设置用于在 Azure AD 中识别应用程序的证书。Sets the certificate identifying the application with Azure AD.
.WithClientSecret(string clientSecret) 设置用于在 Azure AD 中识别应用程序的客户端机密(应用密码)。Sets the client secret (app password) identifying the application with Azure AD.

这些修饰符是互斥的。These modifiers are mutually exclusive. 如果同时提供两者,MSAL 会引发有含义的异常。If you provide both, MSAL will throw a meaningful exception.

修饰符用法示例Example of usage of modifiers

假设你的应用程序是一个仅供你的组织使用的业务线应用程序。Let's assume that your application is a line-of-business application, which is only for your organization. 那么,可编写以下代码:Then you can write:

IPublicClientApplication app;
app = PublicClientApplicationBuilder.Create(clientId)
        .WithAuthority(AzureCloudInstance.AzureChina, AadAuthorityAudience.AzureAdMultipleOrgs)
        .Build();

ADFS 也有一个重写(目前不支持 ADFS 2019):There is also an override for ADFS (ADFS 2019 is currently not supported):

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

最后,如果你是 Azure AD B2C 开发人员,可按如下所示指定租户:Finally, if you are an Azure AD B2C developer, you can specify your tenant like this:

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