如何使用应用服务和 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 的托管标识,应用可以轻松访问其他受 AAD 保护的资源(如 Azure Key Vault)。A managed identity from Azure Active Directory allows your app to easily access other AAD-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. 有关 AAD 中的托管标识的详细信息,请参阅 Azure 资源的托管标识For more about managed identities in AAD, 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 which can be assigned to your app. 一个应用可以具有多个用户分配的标识。An app can have multiple user-assigned identities.

添加系统分配的标识Adding 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 instruction 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><PRINCIPALID> 替换为 GUID。Where <TENANTID> and <PRINCIPALID> are replaced with GUIDs. tenantId 属性标识该标识所属的 AAD 租户。The tenantId property identifies what AAD tenant the identity belongs to. principalId 是应用程序新标识的唯一标识符。The principalId is a unique identifier for the application's new identity. 在 AAD 中,服务主体的名称与你为应用服务或 Azure Functions 实例提供的名称相同。Within AAD, the service principal has the same name that you gave to your App Service or Azure Functions instance.

添加用户分配的标识(预览版)Adding a user-assigned identity (preview)

Note

用户分配的标识现提供预览版。User-assigned identities are currently in preview.

创建带有用户分配符的标识的应用需要创建标识,然后将其资源标识符添加到应用配置中。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

Note

此门户体验正在部署中,可能尚未在所有区域中提供。This portal experience is being deployed and may not yet be available in all regions.

首先,需要创建用户分配的标识资源。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 (preview) 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 and a cotells 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": "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><CLIENTID> 替换为 GUID。Where <PRINCIPALID> and <CLIENTID> are replaced with GUIDs. principalId 是用于 AAD 管理的标识的唯一标识符。The principalId is a unique identifier for the identity which is used for AAD administration. clientId 是应用程序新标识的唯一标识符,用于指定在运行时调用期间要使用的标识。The clientId is a unique identifier for the application's new identity that is used for specifying which identity to use during runtime calls.

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

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

Important

可能需要配置目标资源,允许从应用程序进行访问。You may need to configure the target resource to allow access from your application. 例如,如果请求 Key Vault 的令牌,需要确保已添加包含应用程序标识的访问策略。For example, if you request a token to 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.

在应用服务和 Azure Functions 中,使用简单的 REST 协议获取令牌。There is a simple REST protocol for obtaining a token in App Service and Azure Functions. 对于 .NET 应用程序,Microsoft.Azure.Services.AppAuthentication 库提供此协议的摘要并支持本地开发体验。For .NET applications, the Microsoft.Azure.Services.AppAuthentication library provides an abstraction over this protocol and supports a local development experience.

使用用于.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>
  1. 使用 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);

使用 REST 协议Using the REST protocol

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

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

“MSI_ENDPOINT”是一本地 URL,应用可向其请求令牌。 The MSI_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 应获取其令牌的资源的 AAD 资源 URI。The AAD 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. 目前唯一支持的版本是 "2017-09-01"。"2017-09-01" is currently the only version supported.
secretsecret 标头Header MSI_SECRET 环境变量的值。The value of the MSI_SECRET environment variable. 此标头用于帮助缓解服务器端请求伪造 (SSRF) 攻击。This header is used to help mitigate server-side request forgery (SSRF) attacks.
clientidclientid 查询Query (可选)要使用的用户分配的标识的 ID。(Optional) The ID of the user-assigned identity to be used. 如果省略,则将使用系统分配的标识。If omitted, the system-assigned identity is used.

成功的 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.
expires_onexpires_on 访问令牌的过期时间。The time when the access token expires. 该日期表示为自 1970-01-01T0:0:0Z UTC 至过期时间的秒数。The date is represented as the number of seconds from 1970-01-01T0:0:0Z UTC until the expiration time. 此值用于确定缓存令牌的生存期。This value is used to determine the lifetime of cached tokens.
resourceresource 接收 Web 服务的应用 ID URI。The App ID URI of the receiving web service.
token_typetoken_type 指示令牌类型值。Indicates the token type value. Azure AD 唯一支持的类型是 Bearer。The only type that Azure AD supports is Bearer. 有关持有者令牌的详细信息,请参阅 OAuth 2.0 授权框架:持有者令牌用法 (RFC 6750)For more information about bearer tokens, see The OAuth 2.0 Authorization Framework: Bearer Token Usage (RFC 6750).

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

Note

进程第一次启动时会设置环境变量,因此为应用程序启用托管标识后,可能需要重启应用程序或重新部署其代码,然后才能在代码中使用 MSI_ENDPOINTMSI_SECRETEnvironment variables are set up when the process first starts, so after enabling a managed identity for your application, you may need to restart your application, or redeploy its code, before MSI_ENDPOINT and MSI_SECRET are available to your code.

REST 协议示例REST protocol examples

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

GET /MSI/token?resource=https://vault.azure.cn&api-version=2017-09-01 HTTP/1.1
Host: localhost:4141
Secret: 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": "09/14/2017 00:00:00 PM +00:00",
    "resource": "https://vault.azure.cn",
    "token_type": "Bearer"
}

代码示例Code examples

使用 C# 发出此请求:To make this request in C#:

public static async Task<HttpResponseMessage> GetToken(string resource, string apiversion)  {
    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Add("Secret", Environment.GetEnvironmentVariable("MSI_SECRET"));
    return await client.GetAsync(String.Format("{0}/?resource={1}&api-version={2}", Environment.GetEnvironmentVariable("MSI_ENDPOINT"), resource, apiversion));
}

Tip

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

在 Node.JS 中:In Node.JS:

const rp = require('request-promise');
const getToken = function(resource, apiver, cb) {
    let options = {
        uri: `${process.env["MSI_ENDPOINT"]}/?resource=${resource}&api-version=${apiver}`,
        headers: {
            'Secret': process.env["MSI_SECRET"]
        }
    };
    rp(options)
        .then(cb);
}

在 Python 中:In Python:

import os
import requests

msi_endpoint = os.environ["MSI_ENDPOINT"]
msi_secret = os.environ["MSI_SECRET"]

def get_bearer_token(resource_uri, token_api_version):
    token_auth_uri = f"{msi_endpoint}?resource={resource_uri}&api-version={token_api_version}"
    head_msi = {'Secret':msi_secret}

    resp = requests.get(token_auth_uri, headers=head_msi)
    access_token = resp.json()['access_token']

    return access_token

在 PowerShell 中:In PowerShell:

$apiVersion = "2017-09-01"
$resourceURI = "https://<AAD-resource-URI-for-resource-to-obtain-token>"
$tokenAuthURI = $env:MSI_ENDPOINT + "?resource=$resourceURI&api-version=$apiVersion"
$tokenResponse = Invoke-RestMethod -Method Get -Headers @{"Secret"="$env:MSI_SECRET"} -Uri $tokenAuthURI
$accessToken = $tokenResponse.access_token

删除标识Removing 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. 若要删除所有标识,请在 REST/ARM 模板协议中通过将类型设置为“无”来完成此操作:To remove all identities, in the REST/ARM template protocol, this is done by setting the type to "None":

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

以这种方式删除系统分配的标识也会将它从 AAD 中删除。Removing a system-assigned identity in this way will also delete it from AAD. 删除应用资源时,也将自动从 AAD 中删除系统分配的标识。System-assigned identities are also automatically removed from AAD 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