创建自定义 Azure 资源管理器角色并将其分配给服务主体Create custom Azure Resource Manager role and assign to service principal

IoT Edge 模块实例上的实时视频分析需要可用的 Azure 媒体服务帐户,才能正常工作。Live Video Analytics on IoT Edge module instance needs an active Azure Media Services account for it to function properly. IoT Edge 模块上的实时视频分析与 Azure 媒体服务帐户之间的关系是通过一组模块孪生属性建立的。The relationship between the Live Video Analytics on IoT Edge module and the Azure Media Service account is established via a set of module twin properties. 其中一个孪生属性是服务主体,它使模块实例能够与媒体服务帐户进行通信并触发必要的操作。One of those twin properties is a service principal that enables the module instance to communicate with and trigger necessary operations on the Media Services account. 为了最大程度地减少来自边缘设备滥用和/或意外数据泄露的可能性,此服务主体应拥有最少的权限。To minimize potential misuse and/or accidental data exposure from the edge device, this service principal should have the least amount of privileges.

本文介绍创建自定义 Azure 资源管理器角色的步骤,该角色用于创建服务主体。This article shows you the steps for creating a custom Azure Resource Manager role, which then is used to create a service principal.

先决条件Prerequisites

本文的先决条件如下所示:Prerequisites for this article are as follows:

  • 具有所有者订阅的 Azure 订阅。Azure subscription with owner subscription.
  • 有权创建应用并将服务主体分配给角色的 Azure Active Directory。An Azure Active Directory with privileges to create an app and assign service principal to a role.

检查帐户是否有足够权限的最简方法是使用门户。The easiest way to check whether your account has adequate permissions is through the portal. 请参阅检查所需的权限See Check required permission.

概述Overview

我们将按照以下顺序介绍创建自定义角色并将其与服务主体关联的步骤:We will go over the steps to creating a custom role and linking it with a service principal in the following order:

  1. 如果你没有媒体服务帐户,请创建一个。Create a Media Service account, if you don't already have one.
  2. 创建服务主体。Create a service principal.
  3. 创建具有有限权限的自定义 Azure 资源管理器角色。Create a custom Azure Resource Manager role with limited privileges.
  4. 使用创建的自定义角色“限制”服务主体权限。“Restrict” the service principal privileges using the custom role created.
  5. 运行一个简单的测试,查看是否能够成功地限制服务主体。Run a simple test to see if we are able to successfully restrict the service principal.
  6. 捕获将在 IoT Edge 部署清单中使用的参数。Capture the parameters that will be used in the IoT Edge deployment manifests.

创建媒体服务帐户Create a Media Services account

如果你没有媒体服务帐户,请使用以下步骤创建一个。If you don't have a Media Service account, use the following steps to create one.

  1. 使用以下命令模板将 Azure 订阅设置为默认帐户:Set your Azure subscription as the default account using the following command template:

    az account set --subscription " <yourSubscriptionName or yourSubscriptionId>"
    
  2. 创建资源组存储帐户Create a resource group and a storage account.

  3. 现在,通过使用以下命令模板来创建 Azure 媒体服务帐户:Now, create an Azure Media Service account by using the following command template:

    az ams account create --name <yourAMSAccountName>  --resource-group <yourResouceGroup>  --storage-account <yourStorageAccountName>
    

创建服务主体Create service principal

现在,我们将创建一个新的服务主体并将其关联到媒体服务帐户。We will now create a new service principal and link it to your Media Service account.

如果没有任何身份验证参数,则将基于密码的身份验证与服务主体的随机密码配合使用。Without any authentication parameters, password-based authentication is used with a random password for your service principal.

az ams account sp create --account-name < yourAMSAccountName > --resource-group < yourResouceGroup >

此命令会生成如下响应:This command produces a response like this:

{
  "AadClientId": "00000000-0000-0000-0000-000000000000",
  "AadEndpoint": "https://login.chinacloudapi.cn",
  "AadSecret": "<yourServicePrincipalPassword>",
  "AadTenantId": "00000000-0000-0000-0000-000000000000",
  "AccountName": " <yourAMSAccountName >",
  "ArmAadAudience": "https://management.core.chinacloudapi.cn/",
  "ArmEndpoint": "https://management.chinacloudapi.cn/",
  "Region": "China East 2",
  "ResourceGroup": " <yourResouceGroup >",
  "SubscriptionId": "<yourSubscriptionId>"
}

  1. 具有密码身份验证的服务主体的输出包括密码密钥,在本例中,此密码密钥为“AadSecret”参数。The output for a service principal with password authentication includes the password key that in this case is the "AadSecret" parameter.

    请确保复制此值 - 它不可检索。Make sure you copy this value - it can't be retrieved. 如果忘记了密码,请重置服务主体凭据If you forget the password, reset the service principal credentials.

  2. appId 和租户密钥分别在输出中显示为“AadClientId”和“AadTenantId”。The appId and tenant key appear in the output as "AadClientId" and "AadTenantId" respectively. 它们用于服务主体身份验证。They are used in service principal authentication. 请记录其值,但它们随时可以通过 az ad sp list 检索。Record their values, but they can be retrieved at any point with az ad sp list.

创建自定义角色定义Create a custom role definition

若要创建自定义角色,请按照以下步骤操作:To create a custom role, here are steps you should follow:

  1. 在本地系统上创建角色定义 JSON 文件,并将以下文本保存在该文件中。Create a Role Definition JSON file on your local system and save the following text in the file.

    1. 将 < yourSubscriptionId> 替换为你的 Azure 订阅 IDReplace < yourSubscriptionId> with your Azure Subscription ID

    2. 此角色仅允许执行以下操作:The only actions allowed for this role are:

      • listContainerSas - 帮助模块列出具有共享访问签名 (SAS) 的存储容器 URL,以便上传和下载资产内容。listContainerSas – helps the module list storage container URLs with shared access signatures (SAS) for uploading and downloading asset content.
      • 写入资产 - 帮助模块创建或更新任何资产Write assets – helps the module create or update any asset
      • listEdgePolicies - 列出应用于边缘设备的策略listEdgePolicies – lists the policies that are applied to the edge device
      {
        "Name": "LVAEdge User",
        "IsCustom": true,
        "Description": "Can create assets, view list of containers and view Edge policies",
        "Actions": [
          "Microsoft.Media/mediaservices/assets/listContainerSas/action",
          "Microsoft.Media/mediaservices/assets/write",
          "Microsoft.Media/mediaservices/listEdgePolicies/action"
        ],
        "NotActions": [],
        "DataActions": [],
        "NotDataActions": [],
        "AssignableScopes": [
          "/subscriptions/<yourSubscriptionId>"
        ]
      }
      
  2. 创建完成后,运行以下命令模板以在订阅中创建新的角色定义:Once created, run the following command template to create the new role definition in the subscription:

    az role definition create --role-definition "<location of the Role Definition JSON file >"
    

    成功执行命令后,你将看到以下输出:Upon successful execution of the command, you will see the following output:

    {
      "assignableScopes": [
      "/subscriptions/<yourSubscriptionId>"
      ],
      "description": "Can create assets, view list of containers and view Edge policies",
      "id": "/subscriptions/<yourSubscriptionId>/providers/Microsoft.Authorization/roleDefinitions/<unique name>",
      "name": "<unique name>",
      "permissions": [
        {
          "actions": [
            "Microsoft.Media/mediaservices/assets/listContainerSas/action",
            "Microsoft.Media/mediaservices/assets/write",
            "Microsoft.Media/mediaservices/listEdgePolicies/action",
          ],
          "dataActions": [],
          "notActions": [],
          "notDataActions": []
        }
      ],
      "roleName": " LVAEdge User ",
      "roleType": "CustomRole",
      "type": "Microsoft.Authorization/roleDefinitions"
    }
    

创建角色分配Create role assignment

若要添加角色分配,你需要服务主体的 objectId,才能向该主体分配刚刚创建的自定义角色。To add a role assignment, you will need the objectId of the service principal you want to assign the custom role you just created.

使用以下命令获取 objectId:Use the following command to get the objectId:

az ad sp show --id "<appId>" | Select-String "objectId"

备注

可以从创建服务主体步骤的输出中检索 <appId><appId> can be retrieved from the output of the Create service principal step.

上述命令将输出服务主体的 objectId。The above command will print out the objectId of the service principal.

“objectId” : “<yourObjectId>”,

使用 az role assignment create 命令模板将自定义角色与服务主体关联:Use az role assignment create command template to the link the custom role with the service principal:

az role assignment create --role “LVAEdge User” --assignee-object-id < objectId>    

参数:Parameters:

参数Parameters 说明Description
--role--role 自定义角色名称或 ID。Custom Role name or ID. 在本例中为:“LVAEdge User”。In our case: “LVAEdge User”.
--assignee-object-id--assignee-object-id 将使用的服务主体的对象 ID。Object ID of the service principal you will use.

结果将如下所示:The result will look like:

{
  "canDelegate": null,
  "id": "/subscriptions/<yourSubscriptionId>/providers/Microsoft.Authorization/roleAssignments/<yourCustomRoleId>",
  "name": "<yourCustomRoleId>",
  "principalId": "<yourServicePrincipalId>",
  "principalType": "ServicePrincipal",
  "roleDefinitionId": "/subscriptions/<yourSubscriptionId>/providers/Microsoft.Authorization/roleDefinitions/<yourRoleDefinitionId>",
  "scope": "/subscriptions/<yourSubscriptionId>",
  "type": "Microsoft.Authorization/roleAssignments"
} 

确认角色分配已发生Confirm that role assignment happened

若要确认服务主体现在是否已与刚刚创建的自定义角色关联,请运行以下命令:To confirm that the service principal is now linked with the custom role we just created, run the following command:

az role assignment list  --assignee < objectId>

结果应如下所示:The result should look like:

[
  {
    "canDelegate": null,
    "id": "/subscriptions/xxx/providers/Microsoft.Authorization/roleAssignments/00000000-0000-0000-0000-000000000000",
    "name": "00000000-0000-0000-0000-000000000000",
    "principalId": "<yourServicePrincipalID>",
    "principalName": "<yourServicePrincipalName>",
    "principalType": "ServicePrincipal",
    "roleDefinitionId": "/subscriptions/xxx/providers/Microsoft.Authorization/roleDefinitions/zzz",
    "roleDefinitionName": "LVAEdge User",
    "scope": "/subscriptions/<yourSubscription ID>",
    "type": "Microsoft.Authorization/roleAssignments
  }
]  

查找“roleDefinitionName”,并查看其值是否设置为“LVAEdge User”。Look for the “roleDefinitionName” and see that its value is set to “LVAEdge User”.

这可以确认我们已将自定义用户角色与用于应用程序的服务主体关联。This confirms that we have linked the custom user role with the service principal that is used for our application.

测试服务主体 RBACTest the service principal RBAC

  1. 使用服务主体登录。Login using the Service Principal. 为此,我们将需要 3 条信息,以便 Azure Active Directory 授予我们适当的访问令牌,这些令牌可以从创建服务主体步骤的输出中获取:For this, we will need 3 pieces of information for the Azure Active Directory to grant us the proper access token that we can get from the output of the Create service principal step:

    1. AadClientIDAadClientID
    2. AadSecretAadSecret
    3. AadTenantIdAadTenantId
  2. 现在,让我们尝试使用下面的命令模板登录:Now, lets try to log in using the command template below:

    az login --service-principal --username "< AadClientID>" --password " <AadSecret>" --tenant "<AadTenantId>"
    
  3. 现在,让我们通过尝试创建资源组并确保操作失败,来确定登录是否仅限于具有“LVAEdge User”角色的服务主体。Now, let's see if the login is restricted to the service principal with "LVAEdge User" role by trying to create a resource group to make sure it fails. 运行以下命令:Run the following command:

    az group create --location "china east 2" --name "testresourcegroup"
    

    此命令应会失败,并将如下所示:This command should fail and will look like:

    The client '<AadClientId>' with object id '<AadClientId>' does not have authorization to perform action 'Microsoft.Resources/subscriptions/resourcegroups/write' over scope '/subscriptions/<yourSubscriptionId>/resourcegroups/testresourcegroup' or the scope is invalid. If access was recently granted, please refresh your credentials.
    

后续步骤Next steps

请记下本文中的以下值。Note the following values from this article. 你需要使用这些值配置 IoT Edge 模块上的实时视频分析的孪生属性。有关信息,请参阅模块孪生 JSON 模式These values will be required for you to configure the twin properties of the Live Video Analytics on IoT Edge module, see Module twin JSON schema.

本文中的变量Variable from this article IoT Edge 上的实时视频分析的孪生属性名称Twin property name for Live Video Analytics on IoT Edge
AadSecretAadSecret aadServicePrincipalPasswordaadServicePrincipalPassword
AadTenantIdAadTenantId aadTenantIdaadTenantId
AadClientIdAadClientId aadServicePrincipalAppIdaadServicePrincipalAppId