如何使用应用服务和 Azure Functions 的托管标识How to use managed identities for App Service and Azure Functions

Important

如果应用跨订阅/租户迁移,应用服务和 Azure Functions 的托管标识将不会按预期工作。Managed identities for App Service and Azure Functions will not behave as expected if your app is migrated across subscriptions/tenants. 应用将需要获取新标识,这可以通过禁用并重新启用该功能来完成。The app will need to obtain a new identity, which can be done by disabling and re-enabling the feature. 请参阅下面的删除标识See Removing an identity below. 下游资源还需要更新访问策略才能使用新标识。Downstream resources will also need to have access policies updated to use the new identity.

本主题介绍如何为应用服务和 Azure Functions 应用程序创建托管标识,以及如何使用它来访问其他资源。This topic shows you how to create a managed identity for App Service and Azure Functions applications and how to use it to access other resources. 借助 Azure Active Directory (Azure AD) 的托管标识,应用可以轻松访问其他受 Azure AD 保护的资源(如 Azure Key Vault)。A managed identity from Azure Active Directory (Azure AD) allows your app to easily access other Azure AD-protected resources such as Azure Key Vault. 标识由 Azure 平台托管,无需设置或转交任何机密。The identity is managed by the Azure platform and does not require you to provision or rotate any secrets. 有关 Azure AD 中的托管标识的详细信息,请参阅 Azure 资源的托管标识For more about managed identities in Azure AD, see Managed identities for Azure resources.

你的应用程序可以被授予两种类型的标识:Your application can be granted two types of identities:

  • 系统分配的标识与你的应用程序相绑定,如果删除应用,标识也会被删除。A system-assigned identity is tied to your application and is deleted if your app is deleted. 一个应用只能具有一个系统分配的标识。An app can only have one system-assigned identity.
  • 用户分配的标识是可以分配给应用的独立 Azure 资源。A user-assigned identity is a standalone Azure resource that can be assigned to your app. 一个应用可以具有多个用户分配的标识。An app can have multiple user-assigned identities.

添加系统分配的标识Add a system-assigned identity

若要创建带有系统分配的标识的应用,需在应用程序上设置一个额外的属性。Creating an app with a system-assigned identity requires an additional property to be set on the application.

使用 Azure 门户Using the Azure portal

要在门户中设置托管标识,需先按常规创建应用程序,然后启用该功能。To set up a managed identity in the portal, you will first create an application as normal and then enable the feature.

  1. 按常规在门户中创建应用。Create an app in the portal as you normally would. 在门户中导航到该应用。Navigate to it in the portal.

  2. 如果使用函数应用,请导航到“平台功能”。If using a function app, navigate to Platform features. 对于其他应用类型,请在左侧导航区域向下滚动到“设置”组。For other app types, scroll down to the Settings group in the left navigation.

  3. 选择“标识”。Select Identity.

  4. 在“系统分配的”选项卡中,将“状态”切换为“启用” 。Within the System assigned tab, switch Status to On. 单击“保存” 。Click Save.

    应用服务中的托管标识

使用 Azure CLIUsing the Azure CLI

若要使用 Azure CLI 设置托管标识,需要针对现有应用程序使用 az webapp identity assign 命令:To set up a managed identity using the Azure CLI, you will need to use the az webapp identity assign command against an existing application:

以下步骤将指导你完成使用 CLI 创建 Web 应用并为其分配标识的操作:The following steps will walk you through creating a web app and assigning it an identity using the CLI:

  1. 如果在本地控制台中使用 Azure CLI,首先请使用 az login 登录到 Azure。If you're using the Azure CLI in a local console, first sign in to Azure using az login. 使用与要在其下部署应用程序的 Azure 订阅关联的帐户:Use an account that is associated with the Azure subscription under which you would like to deploy the application:

    az cloud set -n AzureChinaCloud
    az login
    
  2. 使用 CLI 创建 Web 应用程序。Create a web application using the CLI. 有关如何将 CLI 用于应用服务的更多示例,请参阅应用服务 CLI 示例For more examples of how to use the CLI with App Service, see App Service CLI samples:

    az group create --name myResourceGroup --location chinanorth
    az appservice plan create --name myPlan --resource-group myResourceGroup --sku S1
    az webapp create --name myApp --resource-group myResourceGroup --plan myPlan
    
  3. 运行 identity assign 命令为此应用程序创建标识:Run the identity assign command to create the identity for this application:

    az webapp identity assign --name myApp --resource-group myResourceGroup
    

使用 Azure PowerShellUsing Azure PowerShell

Note

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

以下步骤将指导你完成使用 Azure PowerShell 创建 Web 应用并为其分配标识的操作:The following steps will walk you through creating a web app and assigning it an identity using Azure PowerShell:

  1. 根据需要按照 Azure PowerShell 指南中的说明安装 Azure PowerShell,然后运行 Login-AzAccount 以创建与 Azure 的连接。If needed, install the Azure PowerShell using the instructions found in the Azure PowerShell guide, and then run Login-AzAccount to create a connection with Azure.

  2. 使用 Azure PowerShell 创建 Web 应用程序。Create a web application using Azure PowerShell. 有关如何将 Azure PowerShell 用于应用服务的更多示例,请参阅应用服务 PowerShell 示例For more examples of how to use Azure PowerShell with App Service, see App Service PowerShell samples:

    # Create a resource group.
    New-AzResourceGroup -Name myResourceGroup -Location $location
    
    # Create an App Service plan in Free tier.
    New-AzAppServicePlan -Name $webappname -Location $location -ResourceGroupName myResourceGroup -Tier Free
    
    # Create a web app.
    New-AzWebApp -Name $webappname -Location $location -AppServicePlan $webappname -ResourceGroupName myResourceGroup
    
  3. 运行 Set-AzWebApp -AssignIdentity 命令为此应用程序创建标识:Run the Set-AzWebApp -AssignIdentity command to create the identity for this application:

    Set-AzWebApp -AssignIdentity $true -Name $webappname -ResourceGroupName myResourceGroup 
    

使用 Azure 资源管理器模板Using an Azure Resource Manager template

Azure 资源管理器模板可以用于自动化 Azure 资源部署。An Azure Resource Manager template can be used to automate deployment of your Azure resources. 若要详细了解如何部署到应用服务和 Functions,请参阅在应用服务中自动执行资源部署在 Azure Functions 中自动执行资源部署To learn more about deploying to App Service and Functions, see Automating resource deployment in App Service and Automating resource deployment in Azure Functions.

在资源定义包括以下属性,可以创建 Microsoft.Web/sites 类型的任何有标识资源:Any resource of type Microsoft.Web/sites can be created with an identity by including the following property in the resource definition:

"identity": {
    "type": "SystemAssigned"
}

Note

一个应用程序可以同时具有系统分配的标识和用户分配的标识。An application can have both system-assigned and user-assigned identities at the same time. 在这种情况下,type 属性将为 SystemAssigned,UserAssignedIn this case, the type property would be SystemAssigned,UserAssigned

添加系统分配的标识将告知 Azure 为应用程序创建和管理标识。Adding the system-assigned type tells Azure to create and manage the identity for your application.

例如,Web 应用可能如下所示:For example, a web app might look like the following:

{
    "apiVersion": "2016-08-01",
    "type": "Microsoft.Web/sites",
    "name": "[variables('appName')]",
    "location": "[resourceGroup().location]",
    "identity": {
        "type": "SystemAssigned"
    },
    "properties": {
        "name": "[variables('appName')]",
        "serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName'))]",
        "hostingEnvironment": "",
        "clientAffinityEnabled": false,
        "alwaysOn": true
    },
    "dependsOn": [
        "[resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName'))]"
    ]
}

网站创建后,它具有以下附加属性:When the site is created, it has the following additional properties:

"identity": {
    "type": "SystemAssigned",
    "tenantId": "<TENANTID>",
    "principalId": "<PRINCIPALID>"
}

tenantId 属性标识该标识所属的 Azure AD 租户。The tenantId property identifies what Azure AD tenant the identity belongs to. principalId 是应用程序新标识的唯一标识符。The principalId is a unique identifier for the application's new identity. 在 Azure AD 中,服务主体的名称与你为应用服务或 Azure Functions 实例提供的名称相同。Within Azure AD, the service principal has the same name that you gave to your App Service or Azure Functions instance.

添加用户分配的标识Add a user-assigned identity

创建带有用户分配符的标识的应用需要创建标识,然后将其资源标识符添加到应用配置中。Creating an app with a user-assigned identity requires that you create the identity and then add its resource identifier to your app config.

使用 Azure 门户Using the Azure portal

首先,需要创建用户分配的标识资源。First, you'll need to create a user-assigned identity resource.

  1. 根据这些说明创建用户分配的托管标识资源。Create a user-assigned managed identity resource according to these instructions.

  2. 按常规在门户中创建应用。Create an app in the portal as you normally would. 在门户中导航到该应用。Navigate to it in the portal.

  3. 如果使用函数应用,请导航到“平台功能”。If using a function app, navigate to Platform features. 对于其他应用类型,请在左侧导航区域向下滚动到“设置”组。For other app types, scroll down to the Settings group in the left navigation.

  4. 选择“标识”。Select Identity.

  5. 在“用户分配”选项卡中,单击“添加” 。Within the User assigned tab, click Add.

  6. 搜索之前创建的标识并选择它。Search for the identity you created earlier and select it. 单击“添加” 。Click Add.

    应用服务中的托管标识

使用 Azure 资源管理器模板Using an Azure Resource Manager template

Azure 资源管理器模板可以用于自动化 Azure 资源部署。An Azure Resource Manager template can be used to automate deployment of your Azure resources. 若要详细了解如何部署到应用服务和 Functions,请参阅在应用服务中自动执行资源部署在 Azure Functions 中自动执行资源部署To learn more about deploying to App Service and Functions, see Automating resource deployment in App Service and Automating resource deployment in Azure Functions.

通过在资源定义中包含以下块,然后将 <RESOURCEID> 替换为所需标识的资源 ID,就可以创建带有标识的任何 Microsoft.Web/sites 类型的资源:Any resource of type Microsoft.Web/sites can be created with an identity by including the following block in the resource definition, replacing <RESOURCEID> with the resource ID of the desired identity:

"identity": {
    "type": "UserAssigned",
    "userAssignedIdentities": {
        "<RESOURCEID>": {}
    }
}

Note

一个应用程序可以同时具有系统分配的标识和用户分配的标识。An application can have both system-assigned and user-assigned identities at the same time. 在这种情况下,type 属性将为 SystemAssigned,UserAssignedIn this case, the type property would be SystemAssigned,UserAssigned

添加用户分配的类型即告知 Azure 使用为应用程序指定的用户分配的标识。Adding the user-assigned type tells Azure to use the user-assigned identity specified for your application.

例如,Web 应用可能如下所示:For example, a web app might look like the following:

{
    "apiVersion": "2016-08-01",
    "type": "Microsoft.Web/sites",
    "name": "[variables('appName')]",
    "location": "[resourceGroup().location]",
    "identity": {
        "type": "UserAssigned",
        "userAssignedIdentities": {
            "[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', variables('identityName'))]": {}
        }
    },
    "properties": {
        "name": "[variables('appName')]",
        "serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName'))]",
        "hostingEnvironment": "",
        "clientAffinityEnabled": false,
        "alwaysOn": true
    },
    "dependsOn": [
        "[resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName'))]",
        "[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', variables('identityName'))]"
    ]
}

网站创建后,它具有以下附加属性:When the site is created, it has the following additional properties:

"identity": {
    "type": "UserAssigned",
    "userAssignedIdentities": {
        "<RESOURCEID>": {
            "principalId": "<PRINCIPALID>",
            "clientId": "<CLIENTID>"
        }
    }
}

principalId 是用于 Azure AD 管理的标识的唯一标识符。The principalId is a unique identifier for the identity that's used for Azure AD administration. clientId 是应用程序新标识的唯一标识符,用于指定在运行时调用期间要使用的标识。The clientId is a unique identifier for the application's new identity that's used for specifying which identity to use during runtime calls.

获取 Azure 资源的令牌Obtain tokens for Azure resources

应用可以使用其托管标识获取令牌,以访问其他受 Azure AD 保护的资源(如 Azure Key Vault)。An app can use its managed identity to get tokens to access other resources protected by Azure AD, such as Azure Key Vault. 这些令牌代表访问资源的应用程序,而不是应用程序的任何特定用户。These tokens represent the application accessing the resource, and not any specific user of the application.

可能需要配置目标资源,允许从应用程序进行访问。You may need to configure the target resource to allow access from your application. 例如,如果请求用于访问 Key Vault 的令牌,需要确保已添加包含应用程序标识的访问策略。For example, if you request a token to access Key Vault, you need to make sure you have added an access policy that includes your application's identity. 否则,对 Key Vault 的调用将被拒绝,即使其中包含令牌。Otherwise, your calls to Key Vault will be rejected, even if they include the token. 若要详细了解支持 Azure Active Directory 令牌的资源,请参阅支持 Azure AD 身份验证的 Azure 服务To learn more about which resources support Azure Active Directory tokens, see Azure services that support Azure AD authentication.

Important

用于托管标识的后端服务将为每个资源 URI 维护缓存约 8 小时。The back-end services for managed identities maintain a cache per resource URI for around 8 hours. 如果你更新特定目标资源的访问策略并立即检索该资源的令牌,则可以继续获取具有过时权限的缓存令牌,直到该令牌过期。If you update the access policy of a particular target resource and immediately retrieve a token for that resource, you may continue to get a cached token with outdated permissions until that token expires. 目前无法强制刷新令牌。There's currently no way to force a token refresh.

在应用服务和 Azure Functions 中,使用简单的 REST 协议获取令牌。There is a simple REST protocol for obtaining a token in App Service and Azure Functions. 此协议可用于所有应用程序和语言。This can be used for all applications and languages. 对于 .NET 和 Java,Azure SDK 提供了对此协议的抽象,并有助于本地开发体验。For .NET and Java, the Azure SDK provides an abstraction over this protocol and facilitates a local development experience.

使用 REST 协议Using the REST protocol

有托管标识的应用定义了两个环境变量:An app with a managed identity has two environment variables defined:

  • IDENTITY_ENDPOINT - 本地令牌服务的 URL。IDENTITY_ENDPOINT - the URL to the local token service.
  • IDENTITY_HEADER - 用于帮助缓解服务器端请求伪造 (SSRF) 攻击的标头。IDENTITY_HEADER - a header used to help mitigate server-side request forgery (SSRF) attacks. 该值由平台轮换。The value is rotated by the platform.

IDENTITY_ENDPOINT 是一个本地 URL,应用可从其请求令牌。The IDENTITY_ENDPOINT is a local URL from which your app can request tokens. 若要获取资源的令牌,请对此终结点发起 HTTP GET 请求,并包括以下参数:To get a token for a resource, make an HTTP GET request to this endpoint, including the following parameters:

参数名称Parameter name InIn 说明Description
resourceresource 查询Query 应获取其令牌的资源的 Azure AD 资源 URI。The Azure AD resource URI of the resource for which a token should be obtained. 这可以是支持 Azure AD 身份验证的 Azure 服务或任何其他资源 URI 之一。This could be one of the Azure services that support Azure AD authentication or any other resource URI.
api-versionapi-version 查询Query 要使用的令牌 API 版本。The version of the token API to be used. 请使用“2019-08-01”或更高版本。Please use "2019-08-01" or later.
X-IDENTITY-HEADERX-IDENTITY-HEADER 标头Header IDENTITY_HEADER 环境变量的值。The value of the IDENTITY_HEADER environment variable. 此标头用于帮助缓解服务器端请求伪造 (SSRF) 攻击。This header is used to help mitigate server-side request forgery (SSRF) attacks.
client_idclient_id 查询Query (可选)要使用的用户分配的标识的客户端 ID。(Optional) The client ID of the user-assigned identity to be used. 不能在包含 principal_idmi_res_idobject_id 的请求中使用。Cannot be used on a request that includes principal_id, mi_res_id, or object_id. 如果省略所有 ID 参数(client_idprincipal_idobject_idmi_res_id),则使用系统分配的标识。If all ID parameters (client_id, principal_id, object_id, and mi_res_id) are omitted, the system-assigned identity is used.
principal_idprincipal_id 查询Query (可选)要使用的用户分配的标识的主体 ID。(Optional) The principal ID of the user-assigned identity to be used. object_id 是可以改用的别名。object_id is an alias that may be used instead. 不能在包含 client_id、mi_res_id 或 object_id 的请求中使用。Cannot be used on a request that includes client_id, mi_res_id, or object_id. 如果省略所有 ID 参数(client_idprincipal_idobject_idmi_res_id),则使用系统分配的标识。If all ID parameters (client_id, principal_id, object_id, and mi_res_id) are omitted, the system-assigned identity is used.
mi_res_idmi_res_id 查询Query (可选)要使用的用户分配的标识的 Azure 资源 ID。(Optional) The Azure resource ID of the user-assigned identity to be used. 不能在包含 principal_idclient_idobject_id 的请求中使用。Cannot be used on a request that includes principal_id, client_id, or object_id. 如果省略所有 ID 参数(client_idprincipal_idobject_idmi_res_id),则使用系统分配的标识。If all ID parameters (client_id, principal_id, object_id, and mi_res_id) are omitted, the system-assigned identity is used.

Important

如果你要尝试获取用户分配的标识的令牌,必须包含一个可选属性。If you are attempting to obtain tokens for user-assigned identities, you must include one of the optional properties. 否则,令牌服务将尝试获取系统分配的标识令牌,该令牌不一定存在。Otherwise the token service will attempt to obtain a token for a system-assigned identity, which may or may not exist.

成功的 200 OK 响应包括具有以下属性的 JSON 正文:A successful 200 OK response includes a JSON body with the following properties:

属性名称Property name 说明Description
access_tokenaccess_token 请求的访问令牌。The requested access token. 调用 Web 服务可以使用此令牌向接收 Web 服务进行身份验证。The calling web service can use this token to authenticate to the receiving web service.
client_idclient_id 使用的标识的客户端 ID。The client ID of the identity that was used.
expires_onexpires_on 访问令牌过期的时间范围。The timespan when the access token expires. 该日期表示为自“1970-01-01T0:0:0Z UTC”开始的秒数(对应于令牌的 exp 声明)。The date is represented as the number of seconds from "1970-01-01T0:0:0Z UTC" (corresponds to the token's exp claim).
not_beforenot_before 访问令牌生效且可被接受的时间范围。The timespan when the access token takes effect, and can be accepted. 该日期表示为自“1970-01-01T0:0:0Z UTC”开始的秒数(对应于令牌的 nbf 声明)。The date is represented as the number of seconds from "1970-01-01T0:0:0Z UTC" (corresponds to the token's nbf claim).
resourceresource 请求访问令牌时所针对的资源,与请求的 resource 查询字符串参数匹配。The resource the access token was requested for, which matches the resource query string parameter of the request.
token_typetoken_type 指示令牌类型值。Indicates the token type value. Azure AD 支持的唯一一个类型是 FBearer。The only type that Azure AD supports is FBearer. 有关持有者令牌的详细信息,请参阅 OAuth 2.0 授权框架:持有者令牌用法 (RFC 6750)For more information about bearer tokens, see The OAuth 2.0 Authorization Framework: Bearer Token Usage (RFC 6750).

此响应与 Azure AD 服务到服务访问令牌请求的响应相同。This response is the same as the response for the Azure AD service-to-service access token request.

Note

此协议的某个旧版本(使用“2017-09-01”API 版本)使用 secret 标头而不是 X-IDENTITY-HEADER,并且仅接受用户分配的标识的 clientid 属性。An older version of this protocol, using the "2017-09-01" API version, used the secret header instead of X-IDENTITY-HEADER and only accepted the clientid property for user-assigned. 它还返回时间戳格式的 expires_onIt also returned the expires_on in a timestamp format. MSI_ENDPOINT 可用作 IDENTITY_ENDPOINT 的别名,MSI_SECRET 可用作 IDENTITY_HEADER 的别名。MSI_ENDPOINT can be used as an alias for IDENTITY_ENDPOINT, and MSI_SECRET can be used as an alias for IDENTITY_HEADER.

REST 协议示例REST protocol examples

示例请求可能如下例所示:An example request might look like the following:

GET /MSI/token?resource=https://vault.azure.cn&api-version=2019-08-01 HTTP/1.1
Host: localhost:4141
X-IDENTITY-HEADER: 853b9a84-5bfa-4b22-a3f3-0b9a43d9ad8a

示例响应可能如下例所示:And a sample response might look like the following:

HTTP/1.1 200 OK
Content-Type: application/json

{
    "access_token": "eyJ0eXAi…",
    "expires_on": "1586984735",
    "resource": "https://vault.azure.cn",
    "token_type": "Bearer",
    "client_id": "5E29463D-71DA-4FE0-8E69-999B57DB23B0"
}

代码示例Code examples

Tip

对于 .NET 语言,也可使用 Microsoft.Azure.Services.AppAuthentication 而不是自己创建此请求。For .NET languages, you can also use Microsoft.Azure.Services.AppAuthentication instead of crafting this request yourself.

private readonly HttpClient _client;
// ...
public async Task<HttpResponseMessage> GetToken(string resource)  {
    var request = new HttpRequestMessage(HttpMethod.Get, 
        String.Format("{0}/?resource={1}&api-version=2019-08-01", Environment.GetEnvironmentVariable("IDENTITY_ENDPOINT"), resource));
    request.Headers.Add("X-IDENTITY-HEADER", Environment.GetEnvironmentVariable("IDENTITY_HEADER"));
    return await _client.SendAsync(request);
}

使用用于.NET 的 Microsoft.Azure.Services.AppAuthentication 库Using the Microsoft.Azure.Services.AppAuthentication library for .NET

对于 .NET 应用程序和函数,使用托管标识最简单的方法是通过 Microsoft.Azure.Services.AppAuthentication 包。For .NET applications and functions, the simplest way to work with a managed identity is through the Microsoft.Azure.Services.AppAuthentication package. 此库还允许通过 Visual Studio、Azure CLI 或 Active Directory 集成身份验证使用用户帐户,在开发计算机上对代码进行本地测试。This library will also allow you to test your code locally on your development machine, using your user account from Visual Studio, the Azure CLI, or Active Directory Integrated Authentication. 有关此库的本地开发选项的详细信息,请参阅 Microsoft.Azure.Services.AppAuthentication 参考For more on local development options with this library, see the Microsoft.Azure.Services.AppAuthentication reference. 本部分演示如何开始在代码中使用此库。This section shows you how to get started with the library in your code.

  1. 向应用程序添加对 Microsoft.Azure.Services.AppAuthentication 和任何其他必需 NuGet 包的引用。Add references to the Microsoft.Azure.Services.AppAuthentication and any other necessary NuGet packages to your application. 以下示例还使用 Microsoft.Azure.KeyVaultThe below example also uses Microsoft.Azure.KeyVault.

  2. 将以下代码添加到应用程序,以修改为针对相应的资源。Add the following code to your application, modifying to target the correct resource. 此示例演示了使用 Azure Key Vault 的两种方法:This example shows two ways to work with Azure Key Vault:

    using Microsoft.Azure.Services.AppAuthentication;
    using Microsoft.Azure.KeyVault;
    // ...
    var azureServiceTokenProvider = new AzureServiceTokenProvider();
    string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://vault.azure.cn");
    // OR
    var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
    

若要了解有关 Microsoft.Azure.Services.AppAuthentication 及其公开的操作的详细信息,请参阅 Microsoft.Azure.Services.AppAuthentication 参考以及将应用服务和 KeyVault 与 MSI.NET 配合使用示例To learn more about Microsoft.Azure.Services.AppAuthentication and the operations it exposes, see the Microsoft.Azure.Services.AppAuthentication reference and the App Service and KeyVault with MSI .NET sample.

使用用于 Java 的 Azure SDKUsing the Azure SDK for Java

对于 Java 应用程序和函数,使用托管标识的最简单方法是通过用于 Java 的 Azure SDKFor Java applications and functions, the simplest way to work with a managed identity is through the Azure SDK for Java. 本部分演示如何开始在代码中使用此库。This section shows you how to get started with the library in your code.

  1. 添加对 Azure SDK 库的引用。Add a reference to the Azure SDK library. 对于 Maven 项目,可以将此代码片段添加到项目的 POM 文件的 dependencies 节:For Maven projects, you might add this snippet to the dependencies section of the project's POM file:

    <dependency>
        <groupId>com.microsoft.azure</groupId>
        <artifactId>azure</artifactId>
        <version>1.23.0</version>
    </dependency>
    
  2. 使用 AppServiceMSICredentials 对象进行身份验证。Use the AppServiceMSICredentials object for authentication. 此示例演示如何使用此机制来处理 Azure Key Vault:This example shows how this mechanism may be used for working with Azure Key Vault:

    import com.microsoft.azure.AzureEnvironment;
    import com.microsoft.azure.management.Azure;
    import com.microsoft.azure.management.keyvault.Vault
    //...
    Azure azure = Azure.authenticate(new AppServiceMSICredentials(AzureEnvironment.AZURE))
            .withSubscription(subscriptionId);
    Vault myKeyVault = azure.vaults().getByResourceGroup(resourceGroup, keyvaultName);
    
    

删除标识Remove an identity

可以使用门户、PowerShell 或 CLI 以与创建时相同的方式禁用此功能,从而删除系统分配的标识。A system-assigned identity can be removed by disabling the feature using the portal, PowerShell, or CLI in the same way that it was created. 可以单独删除用户分配的标识。User-assigned identities can be removed individually. 若要删除所有标识,请在 ARM 模板中将类型设置为“None”:To remove all identities, set the type to "None" in the ARM template:

"identity": {
    "type": "None"
}

以这种方式删除系统分配的标识也会将它从 Azure AD 中删除。Removing a system-assigned identity in this way will also delete it from Azure AD. 删除应用资源时,也将自动从 Azure AD 中删除系统分配的标识。System-assigned identities are also automatically removed from Azure AD when the app resource is deleted.

Note

还可以设置一个应用程序设置 (WEBSITE_DISABLE_MSI),它只禁用本地令牌服务。There is also an application setting that can be set, WEBSITE_DISABLE_MSI, which just disables the local token service. 但是,它会原地保留标识,工具仍然会将托管标识显示为“打开”或“启用”。However, it leaves the identity in place, and tooling will still show the managed identity as "on" or "enabled." 因此,建议不要使用此设置。As a result, use of this setting is not recommended.

后续步骤Next steps