使用 .NET 向 Azure Key Vault 进行服务到服务身份验证Service-to-service authentication to Azure Key Vault using .NET

备注

本文所述的身份验证方法不再被视为最佳做法。The authentication methods documented in this article are no longer considered best practices. 我们建议你采用如何向 Azure Key Vault 进行身份验证中已更新的身份验证方法。We encourage you to adopt the updated authentication methods in How to authenticate to Azure Key Vault.

若要对 Azure Key Vault 进行身份验证,需要提供 Azure Active Directory (Azure AD) 凭据(共享机密或证书)。To authenticate to Azure Key Vault, you need an Azure Active Directory (Azure AD) credential, either a shared secret or a certificate.

管理此类凭据可能很困难。Managing such credentials can be difficult. 可以考虑将凭据包含在源或配置文件中,以此将其绑定到应用中。It's tempting to bundle credentials into an app by including them in source or configuration files. 用于 .NET 库的 Microsoft.Azure.Services.AppAuthentication 简化了此问题。The Microsoft.Azure.Services.AppAuthentication for .NET library simplifies this problem. 它使用开发人员的凭据在本地开发期间进行身份验证。It uses the developer's credentials to authenticate during local development. 随后将解决方案部署到 Azure 时,该库会自动切换到应用程序凭据。When the solution is later deployed to Azure, the library automatically switches to application credentials. 在本地开发期间使用开发人员凭据更安全,因为不需创建 Azure AD 凭据,或者不需在开发人员之间共享凭据。Using developer credentials during local development is more secure because you don't need to create Azure AD credentials or share credentials between developers.

Microsoft.Azure.Services.AppAuthentication 库自动管理身份验证,这样你就可以专注于自己的解决方案而非凭据。The Microsoft.Azure.Services.AppAuthentication library manages authentication automatically, which in turn lets you focus on your solution, rather than your credentials. 该库支持使用 Microsoft Visual Studio、Azure CLI 或 Azure AD 集成身份验证进行本地开发。It supports local development with Microsoft Visual Studio, Azure CLI, or Azure AD Integrated Authentication. 部署到支持托管标识的 Azure 资源时,该库会自动使用 Azure 资源的托管标识When deployed to an Azure resource that supports a managed identity, the library automatically uses managed identities for Azure resources. 不需代码或配置更改。No code or configuration changes are required. 当托管标识不可用时,或者当开发人员的安全上下文不能在本地开发期间确定时,该库还支持直接使用 Azure AD 客户端凭据The library also supports direct use of Azure AD client credentials when a managed identity isn't available, or when the developer's security context can't be determined during local development.

先决条件Prerequisites

  • Visual Studio 2019Visual Studio 2017 v15.5Visual Studio 2019 or Visual Studio 2017 v15.5.

  • Visual Studio 的应用身份验证扩展以 Visual Studio 2017 Update 5 的独立扩展形式发布,与 Update 6 及更高版本中的产品绑定在一起。The App Authentication extension for Visual Studio, available as a separate extension for Visual Studio 2017 Update 5 and bundled with the product in Update 6 and later. 使用 Update 6 或更高版本时,可以验证是否安装了应用身份验证扩展,方法是在 Visual Studio 安装程序中选择 Azure 开发工具。With Update 6 or later, you can verify the installation of the App Authentication extension by selecting Azure Development tools from within the Visual Studio installer.

使用库Using the library

对于 .NET 应用程序,若要使用托管标识,最简单的方式是通过 Microsoft.Azure.Services.AppAuthentication 包。For .NET applications, the simplest way to work with a managed identity is through the Microsoft.Azure.Services.AppAuthentication package. 下面介绍如何入门:Here's how to get started:

  1. 选择“工具” > “NuGet 包管理器” > “管理解决方案的 NuGet 包”,向应用程序添加对 Microsoft.Azure.Services.AppAuthenticationMicrosoft.Azure.KeyVault NuGet 包的引用。 Select Tools > NuGet Package Manager > Manage NuGet Packages for Solution to add references to the Microsoft.Azure.Services.AppAuthentication and Microsoft.Azure.KeyVault NuGet packages to your project.

  2. 添加以下代码:Add the following code:

    using Microsoft.Azure.Services.AppAuthentication;
    using Microsoft.Azure.KeyVault;
    
    // Instantiate a new KeyVaultClient object, with an access token to Key Vault
    var azureServiceTokenProvider1 = new AzureServiceTokenProvider();
    var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider1.KeyVaultTokenCallback));
    
    // Optional: Request an access token to other Azure services
    var azureServiceTokenProvider2 = new AzureServiceTokenProvider();
    string accessToken = await azureServiceTokenProvider2.GetAccessTokenAsync("https://management.chinacloudapi.cn/").ConfigureAwait(false);
    

AzureServiceTokenProvider 类将令牌缓存在内存中,在过期前才将其从 Azure AD 检索出来。The AzureServiceTokenProvider class caches the token in memory and retrieves it from Azure AD just before expiration. 因此,不再需要在调用 GetAccessTokenAsync 方法之前检查是否过期。So, you no longer have to check the expiration before calling the GetAccessTokenAsync method. 在需要使用令牌时直接调用该方法即可。Just call the method when you want to use the token.

GetAccessTokenAsync 方法需要资源标识符。The GetAccessTokenAsync method requires a resource identifier. 若要详细了解 Microsoft Azure 服务,请参阅什么是 Azure 资源的托管标识To learn more about Microsoft Azure services, see What is managed identities for Azure resources.

本地开发身份验证Local development authentication

对于本地开发,有两种主要的身份验证方案:对 Azure 服务进行身份验证对自定义服务进行身份验证For local development, there are two primary authentication scenarios: authenticating to Azure services, and authenticating to custom services.

向 Azure 服务进行身份验证Authenticating to Azure Services

本地计算机不支持 Azure 资源的托管标识。Local machines don't support managed identities for Azure resources. 因此,Microsoft.Azure.Services.AppAuthentication 库使用开发人员凭据在本地开发环境中运行。As a result, the Microsoft.Azure.Services.AppAuthentication library uses your developer credentials to run in your local development environment. 当解决方案部署到 Azure 时,该库使用托管标识切换到 OAuth 2.0 客户端凭据授予流。When the solution is deployed to Azure, the library uses a managed identity to switch to an OAuth 2.0 client credential grant flow. 此方法意味着可以对同一代码进行本地和远程测试,无需担心。This approach means you can test the same code locally and remotely without worry.

对于本地开发,AzureServiceTokenProvider 使用 Visual StudioAzure 命令行界面 (CLI) 或 Azure AD 集成身份验证提取令牌。For local development, AzureServiceTokenProvider fetches tokens using Visual Studio, Azure command-line interface (CLI), or Azure AD Integrated Authentication. 将按顺序尝试每个选项,该库会使用获得成功的第一个选项。Each option is tried sequentially and the library uses the first option that succeeds. 如果没有选项成功,则会引发一个包含详细信息的 AzureServiceTokenProviderException 意外。If no option works, an AzureServiceTokenProviderException exception is thrown with detailed information.

使用 Visual Studio 进行身份验证Authenticating with Visual Studio

若要使用 Visual Studio 进行身份验证:To authenticate by using Visual Studio:

  1. 登录到 Visual Studio,并使用“工具”>“选项”打开“选项”。 Sign in to Visual Studio and use Tools > Options to open Options.

  2. 选择“Azure 服务身份验证”,选择用于本地开发的帐户,然后选择“确定”。 Select Azure Service Authentication, choose an account for local development, and select OK.

如果在使用 Visual Studio 时遇到问题,例如有关令牌提供程序文件的错误,请仔细检查上述步骤。If you run into problems using Visual Studio, such as errors that involve the token provider file, carefully review the preceding steps.

可能需要对开发人员令牌重新进行身份验证。You may need to reauthenticate your developer token. 为此,请选择“工具”>“选项”,然后选择“Azure 服务身份验证”。 To do so, select Tools > Options, and then select Azure Service Authentication. 找到所选帐户下的“重新进行身份验证”链接。Look for a Re-authenticate link under the selected account. 选择该链接进行身份验证。Select it to authenticate.

使用 Azure CLI 进行身份验证Authenticating with Azure CLI

若要使用 Azure CLI 进行本地开发,请确保安装 Azure CLI v2.0.12 或更高版本。To use Azure CLI for local development, be sure you have version Azure CLI v2.0.12 or later.

使用 Azure CLI:To use Azure CLI:

  1. 在 Windows 任务栏中搜索 Azure CLI,打开“Microsoft Azure 命令提示符”。Search for Azure CLI in the Windows Taskbar to open the Microsoft Azure Command Prompt.

  2. 登录到 Azure 门户:运行 az login 登录到 Azure。Sign in to the Azure portal: az login to sign in to Azure.

  3. 通过输入“az account get-access-token --resource https://vault.azure.cn”来验证访问权限。Verify access by entering az account get-access-token --resource https://vault.azure.cn. 如果收到错误,请检查是否正确安装了适当版本的 Azure CLI。If you receive an error, check that the right version of Azure CLI is correctly installed.

    如果未将 Azure CLI 安装到默认目录,则可能会收到错误,指出 AzureServiceTokenProvider 找不到 Azure CLI 的路径。If Azure CLI isn't installed to the default directory, you may receive an error reporting that AzureServiceTokenProvider can't find the path for Azure CLI. 请使用 AzureCLIPath 环境变量来定义 Azure CLI 安装文件夹。Use the AzureCLIPath environment variable to define the Azure CLI installation folder. AzureServiceTokenProvider 在需要时将 AzureCLIPath 环境变量中指定的目录添加到 Path 环境变量。AzureServiceTokenProvider adds the directory specified in the AzureCLIPath environment variable to the Path environment variable when necessary.

  4. 如果使用多个帐户登录到 Azure CLI,或者帐户可以访问多个订阅,则需指定要使用的订阅。If you're signed in to Azure CLI using multiple accounts or your account has access to multiple subscriptions, you need to specify the subscription to use. 输入命令 az account set --subscription <订阅 ID>Enter the command az account set --subscription .

此命令仅在发生故障时生成输出。This command generates output only on failure. 若要验证当前帐户设置,请输入命令 az account listTo verify the current account settings, enter the command az account list.

使用 Azure AD 身份验证进行身份验证Authenticating with Azure AD authentication

若要使用 Azure AD 身份验证,请验证:To use Azure AD authentication, verify that:

向自定义服务进行身份验证Authenticating to custom services

当某个服务调用 Azure 服务时,上述步骤适用,因为 Azure 服务允许访问用户和应用程序。When a service calls Azure services, the previous steps work because Azure services allow access to both users and applications.

创建调用自定义服务的服务时,请使用 Azure AD 客户端凭据进行本地开发身份验证。When creating a service that calls a custom service, use Azure AD client credentials for local development authentication. 有两个选项:There are two options:

  • 使用服务主体登录到 Azure:Use a service principal to sign into Azure:

    1. 创建服务主体。Create a service principal. 有关详细信息,请参阅使用 Azure CLI 创建 Azure 服务主体For more information, see Create an Azure service principal with Azure CLI.

    2. 在 Azure CLI 中使用以下命令登录:Use Azure CLI to sign in with the following command:

      az cloud set -n AzureChinaCloud
      az login --service-principal -u <principal-id> --password <password> --tenant <tenant-id> --allow-no-subscriptions
      

      由于服务主体可能没有订阅访问权限,因此请使用 --allow-no-subscriptions 参数。Because the service principal may not have access to a subscription, use the --allow-no-subscriptions argument.

  • 使用环境变量来指定服务主体详细信息。Use environment variables to specify service principal details. 有关详细信息,请参阅使用服务主体运行应用程序For more information, see Running the application using a service principal.

登录到 Azure 后,AzureServiceTokenProvider 会使用服务主体来检索本地开发的令牌。After you've signed in to Azure, AzureServiceTokenProvider uses the service principal to retrieve a token for local development.

此方法仅适用于本地开发。This approach applies only to local development. 当解决方案部署到 Azure 时,该库会切换到托管标识以进行身份验证。When your solution is deployed to Azure, the library switches to a managed identity for authentication.

使用托管标识或用户分配标识运行应用程序Running the application using managed identity or user-assigned identity

在启用托管标识的 Azure 应用服务或 Azure VM 上运行代码时,库自动使用托管标识。When you run your code on an Azure App Service or an Azure VM with a managed identity enabled, the library automatically uses the managed identity. 无需更改代码,但托管标识必须对密钥保管库具有 GET 权限。No code changes are required, but the managed identity must have GET permissions for the key vault. 可以通过密钥保管库的访问策略为托管标识授予 GET 权限。You can give the managed identity GET permissions through the key vault's Access Policies.

或者,可以使用用户分配的标识进行身份验证。Alternatively, you may authenticate with a user-assigned identity. 有关用户分配的标识的详细信息,请参阅关于 Azure 资源的托管标识For more information on user-assigned identities, see About Managed Identities for Azure resources. 若要使用用户分配的标识进行身份验证,需要在连接字符串中指定用户分配的标识的客户端 ID。To authenticate with a user-assigned identity, you need to specify the Client ID of the user-assigned identity in the connection string. 连接字符串支持中已指定连接字符串。The connection string is specified in Connection String Support.

使用服务主体运行应用程序Running the application using a Service Principal

可能需要创建一个用于身份验证的 Azure AD 客户端凭据。It may be necessary to create an Azure AD Client credential to authenticate. 在以下示例中,可能会发生这种情况:This situation may happen in the following examples:

  • 代码运行在本地开发环境中,但没有使用开发人员的标识。Your code runs on a local development environment, but not under the developer's identity. 例如,Service Fabric 使用 NetworkService 帐户进行本地开发。Service Fabric, for example, uses the NetworkService account for local development.

  • 代码在本地开发环境中运行,而身份验证则通过自定义服务进行,因此不能使用开发人员标识。Your code runs on a local development environment and you authenticate to a custom service, so you can't use your developer identity.

  • 代码在尚不支持 Azure 资源的托管标识的 Azure 计算资源(例如 Azure Batch)上运行。Your code is running on an Azure compute resource that doesn't yet support managed identities for Azure resources, such as Azure Batch.

可通过三种主要方法使用服务主体来运行应用程序。There are three primary methods of using a Service Principal to run your application. 若要使用其中的任何方法,必须先创建服务主体。To use any of them, you must first create a service principal. 有关详细信息,请参阅使用 Azure CLI 创建 Azure 服务主体For more information, see Create an Azure service principal with Azure CLI.

使用本地密钥存储中的证书登录到 Azure ADUse a certificate in local keystore to sign into Azure AD

  1. 使用 Azure CLI az ad sp create-for-rbac 命令创建服务主体证书。Create a service principal certificate using the Azure CLI az ad sp create-for-rbac command.

    az ad sp create-for-rbac --create-cert
    

    此命令创建一个存储在主目录中的 .pem 文件(私钥)。This command creates a .pem file (private key) that's stored in your home directory. 将此证书部署到 LocalMachineCurrentUser 存储。Deploy this certificate to either the LocalMachine or CurrentUser store.

    重要

    CLI 命令生成一个 .pem 文件,但 Windows 原生仅支持 PFX 证书。The CLI command generates a .pem file, but Windows only provides native support for PFX certificates. 若要改为生成 PFX 证书,请使用下面所示的 PowerShell 命令:使用自签名证书创建服务主体To generate a PFX certificate instead, use the PowerShell commands shown here: Create service principal with self-signed certificate. 这些命令也会自动部署证书。These commands automatically deploy the certificate as well.

  2. 将名为 AzureServicesAuthConnectionString 的环境变量设置为以下值:Set an environment variable named AzureServicesAuthConnectionString to the following value:

    RunAs=App;AppId={AppId};TenantId={TenantId};CertificateThumbprint={Thumbprint};
          CertificateStoreLocation={CertificateStore}
    

    将 {AppId}、{TenantId} 和 {Thumbprint} 替换为步骤 1 中生成的值。Replace {AppId}, {TenantId}, and {Thumbprint} with values generated in Step 1. 根据部署计划,将 {CertificateStore} 替换为 LocalMachine` 或 CurrentUserReplace {CertificateStore} with either LocalMachine` or CurrentUser, based on your deployment plan.

  3. 运行应用程序。Run the application.

使用共享机密凭据登录到 Azure ADUse a shared secret credential to sign into Azure AD

  1. 结合 --sdk-auth 参数使用 Azure CLI az ad sp create-for-rbac 命令创建包含密码的服务主体证书。Create a service principal certificate with a password using the Azure CLI az ad sp create-for-rbac command with the --sdk-auth parameter.

    az ad sp create-for-rbac --sdk-auth
    
  2. 将名为 AzureServicesAuthConnectionString 的环境变量设置为以下值:Set an environment variable named AzureServicesAuthConnectionString to the following value:

    RunAs=App;AppId={AppId};TenantId={TenantId};AppKey={ClientSecret}
    

    {AppId}{TenantId}{ClientSecret} 替换为步骤 1 中生成的值。Replace {AppId}, {TenantId}, and {ClientSecret} with values generated in Step 1.

  3. 运行应用程序。Run the application.

一切正确设置以后,不需进一步更改代码。Once everything's set up correctly, no further code changes are necessary. AzureServiceTokenProvider 使用环境变量和证书向 Azure AD 进行身份验证。AzureServiceTokenProvider uses the environment variable and the certificate to authenticate to Azure AD.

使用 Key Vault 中的证书登录到 Azure ADUse a certificate in Key Vault to sign into Azure AD

使用此选项可将服务主体的客户端证书存储在 Key Vault 中,并将其用于服务主体身份验证。This option lets you store a service principal's client certificate in Key Vault and use it for service principal authentication. 在以下情况下,可以使用此选项:You may use this option for the following scenarios:

  • 本地身份验证:你想要使用显式服务主体进行身份验证,并希望将服务主体凭据安全保存在 Key Vault 中。Local authentication, where you want to authenticate using an explicit service principal, and want to keep the service principal credential securely in a key vault. 开发人员帐户必须有权访问 Key Vault。Developer account must have access to the key vault.

  • 从 Azure 进行身份验证:要使用显式凭据,并希望将服务主体凭据安全保存在 Key Vault 中。Authentication from Azure where you want to use explicit credential and want to keep the service principal credential securely in a key vault. 对于跨租户方案,可以使用此选项。You might use this option for a cross-tenant scenario. 托管标识必须有权访问 Key Vault。Managed identity must have access to key vault.

托管标识或开发人员标识必须有权从 Key Vault 检索客户端证书。The managed identity or your developer identity must have permission to retrieve the client certificate from the Key Vault. AppAuthentication 库使用检索到的证书作为服务主体的客户端凭据。The AppAuthentication library uses the retrieved certificate as the service principal's client credential.

若要使用客户端证书进行服务主体身份验证:To use a client certificate for service principal authentication:

  1. 创建一个服务主体证书,并自动将其存储在 Key Vault 中。Create a service principal certificate and automatically store it in your Key Vault. 使用 Azure CLI az ad sp create-for-rbac --keyvault <keyvaultname> --cert <certificatename> --create-cert --skip-assignment 命令:Use the Azure CLI az ad sp create-for-rbac --keyvault <keyvaultname> --cert <certificatename> --create-cert --skip-assignment command:

    az ad sp create-for-rbac --keyvault <keyvaultname> --cert <certificatename> --create-cert --skip-assignment
    

    证书标识符是采用 https://<keyvaultname>.vault.azure.cn/secrets/<certificatename> 格式的 URLThe certificate identifier will be a URL in the format https://<keyvaultname>.vault.azure.cn/secrets/<certificatename>

  2. 请将此连接字符串中的 {KeyVaultCertificateSecretIdentifier} 替换为证书标识符:Replace {KeyVaultCertificateSecretIdentifier} in this connection string with the certificate identifier:

    RunAs=App;AppId={TestAppId};KeyVaultCertificateSecretIdentifier={KeyVaultCertificateSecretIdentifier}
    

    例如,如果 Key Vault 名为 myKeyVault,而你创建了名为 myCert 的证书,则证书标识符为:For instance, if your key vault was called myKeyVault and you created a certificate called myCert, the certificate identifier would be:

    RunAs=App;AppId={TestAppId};KeyVaultCertificateSecretIdentifier=https://myKeyVault.vault.azure.cn/secrets/myCert
    

连接字符串支持Connection String Support

默认情况下,AzureServiceTokenProvider 使用多种方法来检索令牌。By default, AzureServiceTokenProvider uses multiple methods to retrieve a token.

若要控制此过程,请使用传递到 AzureServiceTokenProvider 构造函数或在 AzureServicesAuthConnectionString 环境变量中指定的连接字符串。To control the process, use a connection string passed to the AzureServiceTokenProvider constructor or specified in the AzureServicesAuthConnectionString environment variable.

可以使用以下选项:The following options are supported:

连接字符串选项Connection string option 方案Scenario 注释Comments
RunAs=Developer; DeveloperTool=AzureCli 本地开发Local development AzureServiceTokenProvider 使用 AzureCli 获取令牌。AzureServiceTokenProvider uses AzureCli to get token.
RunAs=Developer; DeveloperTool=VisualStudio 本地开发Local development AzureServiceTokenProvider 使用 Visual Studio 获取令牌。AzureServiceTokenProvider uses Visual Studio to get token.
RunAs=CurrentUser 本地开发Local development AzureServiceTokenProvider 使用 Azure AD 集成身份验证获取令牌。AzureServiceTokenProvider uses Azure AD Integrated Authentication to get token.
RunAs=App Azure 资源的托管标识Managed identities for Azure resources AzureServiceTokenProvider 使用托管标识获取令牌。AzureServiceTokenProvider uses a managed identity to get token.
RunAs=App;AppId={ClientId of user-assigned identity} Azure 资源的用户分配标识User-assigned identity for Azure resources AzureServiceTokenProvider 使用用户分配的标识获取令牌。AzureServiceTokenProvider uses a user-assigned identity to get token.
RunAs=App;AppId={TestAppId};KeyVaultCertificateSecretIdentifier={KeyVaultCertificateSecretIdentifier} 自定义服务身份验证Custom services authentication KeyVaultCertificateSecretIdentifier 是证书的机密标识符。KeyVaultCertificateSecretIdentifier is the certificate's secret identifier.
RunAs=App;AppId={AppId};TenantId={TenantId};CertificateThumbprint={Thumbprint};CertificateStoreLocation={LocalMachine or CurrentUser} 服务主体Service principal AzureServiceTokenProvider 使用证书从 Azure AD 获取令牌。AzureServiceTokenProvider uses certificate to get token from Azure AD.
RunAs=App;AppId={AppId};TenantId={TenantId};CertificateSubjectName={Subject};CertificateStoreLocation={LocalMachine or CurrentUser} 服务主体Service principal AzureServiceTokenProvider 使用证书从 Azure AD 获取令牌AzureServiceTokenProvider uses certificate to get token from Azure AD
RunAs=App;AppId={AppId};TenantId={TenantId};AppKey={ClientSecret} 服务主体Service principal AzureServiceTokenProvider 使用机密从 Azure AD 获取令牌。AzureServiceTokenProvider uses secret to get token from Azure AD.

示例Samples

若要了解 Microsoft.Azure.Services.AppAuthentication 库的运作方式,请参阅以下代码示例。To see the Microsoft.Azure.Services.AppAuthentication library in action, refer to the following code samples.

AppAuthentication 故障排除AppAuthentication Troubleshooting

本地开发过程中出现的常见问题Common issues during local development

未安装 Azure CLI、未登录,或者未使用最新版本Azure CLI is not installed, you're not logged in, or you don't have the latest version

运行 az account get-access-token,确定 Azure CLI 是否显示令牌。Run az account get-access-token to see if Azure CLI shows a token for you. 如果输出中显示 no such program found,请安装最新版本的 Azure CLIIf it says no such program found, install the latest version of the Azure CLI. 系统可能会提示你登录。You may be prompted to sign in.

AzureServiceTokenProvider 找不到 Azure CLI 的路径AzureServiceTokenProvider can't find the path for Azure CLI

AzureServiceTokenProvider 在默认安装位置查找 Azure CLI。AzureServiceTokenProvider looks for Azure CLI at its default install locations. 如果找不到 Azure CLI,请将环境变量 AzureCLIPath 设置为 Azure CLI 的安装文件夹。If it can't find Azure CLI, set environment variable AzureCLIPath to the Azure CLI installation folder. AzureServiceTokenProvider 会将该环境变量添加到 Path 环境变量中。AzureServiceTokenProvider will add the environment variable to the Path environment variable.

使用多个帐户登录到了 Azure CLI、同一个帐户有权访问多个租户中的订阅,或者在本地开发期间尝试发出调用时收到“拒绝访问”错误You're logged into Azure CLI using multiple accounts, the same account has access to subscriptions in multiple tenants, or you get an Access Denied error when trying to make calls during local development

使用 Azure CLI 将默认订阅设置为包含所要使用的帐户的订阅。Using Azure CLI, set the default subscription to one that has the account you want to use. 该订阅必须位于你要访问的资源所在的同一租户中:az account set --subscription [订阅 ID]The subscription must be in the same tenant as the resource you want to access: az account set --subscription [subscription-id]. 如果未显示任何输出,则表示命令成功。If no output is seen, it succeeded. 使用 az account list 验证适当的帐户现在是否为默认帐户。Verify the right account is now the default using az account list.

环境中出现的常见问题Common issues across environments

未授权访问、访问被拒绝、禁止访问或类似错误Unauthorized access, access denied, forbidden, or similar error

使用的主体无法访问其尝试访问的资源。The principal used doesn't have access to the resource it's trying to access. 为你的用户帐户或应用服务的 MSI 授予对资源的“参与者”访问权限。Grant either your user account or the App Service's MSI "Contributor" access to a resource. 向哪个主体授予此权限取决于是在本地计算机上运行示例,还是在 Azure 中将示例部署到应用服务。Which one depends on whether you're running the sample on your local computer or deployed in Azure to your App Service. 某些资源(例如 Key Vault)还具有自身的访问策略,可以使用这些策略向用户、应用和组等主体授予访问权限。Some resources, like key vaults, also have their own access policies that you use grant access to principals, such as users, apps, and groups.

部署到 Azure 应用服务后出现的常见问题Common issues when deployed to Azure App Service

未在应用服务中设置托管标识Managed identity isn't set up on the App Service

使用 Kudu 调试控制台检查环境变量 MSI_ENDPOINT 和 MSI_SECRET 是否存在。Check the environment variables MSI_ENDPOINT and MSI_SECRET exist using Kudu debug console. 如果这些环境变量不存在,则不会在应用服务中启用托管标识。If these environment variables don't exist, Managed Identity isn't enabled on the App Service.

在本地与 IIS 一起部署时出现的常见问题Common issues when deployed locally with IIS

在 IIS 中调试应用时无法检索令牌Can't retrieve tokens when debugging app in IIS

默认情况下,AppAuth 在 IIS 的不同用户上下文中运行。By default, AppAuth runs in a different user context in IIS. 正因如此,它无权使用你的开发人员标识来检索访问令牌。That's why it doesn't have access to use your developer identity to retrieve access tokens. 可通过以下两个步骤,将 IIS 配置为在你的用户上下文中运行:You can configure IIS to run with your user context with the following two steps: