Поделиться через


Assign Azure roles using the REST API

Управление доступом на основе ролей Azure (Azure RBAC) — это система авторизации, используемая для управления доступом к ресурсам в Azure. To grant access, you assign roles to users, groups, service principals, or managed identities at a particular scope. This article describes how to assign roles using the REST API.

Предпосылки

Чтобы назначать роли Azure необходимо наличие:

Необходимо использовать следующие версии:

  • 2015-07-01 or later to assign an Azure role
  • 2018-09-01-preview or later to assign an Azure role to a new service principal

Дополнительные сведения см. в версиях API Azure RBAC REST APIs.

Назначьте роль в Azure

To assign a role, use the Role Assignments - Create REST API and specify the security principal, role definition, and scope. To call this API, you must have access to the Microsoft.Authorization/roleAssignments/write action, such as Role Based Access Control Administrator.

  1. Use the Role Definitions - List REST API or see Built-in roles to get the identifier for the role definition you want to assign.

  2. Use a GUID tool to generate a unique identifier that will be used for the role assignment identifier. Идентификатор имеет формат: 00000000-0000-0000-0000-000000000000

  3. Начните со следующего запроса и текста:

    PUT https://management.azure.com/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentId}?api-version=2022-04-01
    
    {
      "properties": {
        "roleDefinitionId": "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}",
        "principalId": "{principalId}"
      }
    }
    
  4. Within the URI, replace {scope} with the scope for the role assignment.

    Область действия Тип
    providers/Microsoft.Management/managementGroups/{groupId1} Группа управления
    subscriptions/{subscriptionId1} Подписка
    subscriptions/{subscriptionId1}/resourceGroups/myresourcegroup1 Группа ресурсов
    subscriptions/{subscriptionId1}/resourceGroups/myresourcegroup1/providers/microsoft.web/sites/mysite1 Ресурс

    In the previous example, microsoft.web is a resource provider that refers to an App Service instance. Аналогичным образом можно использовать любые другие поставщики ресурсов и указать область. Дополнительные сведения см. в статье Поставщики и типы ресурсов Azure и Операции поставщиков ресурсов Azure.

  5. Replace {roleAssignmentId} with the GUID identifier of the role assignment.

  6. Within the request body, replace {scope} with the same scope as in the URI.

  7. Replace {roleDefinitionId} with the role definition identifier.

  8. Replace {principalId} with the object identifier of the user, group, or service principal that will be assigned the role.

The following request and body assigns the Backup Reader role to a user at subscription scope:

PUT https://management.azure.com/subscriptions/{subscriptionId1}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentId1}?api-version=2022-04-01
{
  "properties": {
    "roleDefinitionId": "/subscriptions/{subscriptionId1}/providers/Microsoft.Authorization/roleDefinitions/a795c7a0-d4a2-40c1-ae25-d81f01202912",
    "principalId": "{objectId1}"
  }
}

Ниже приведен пример выходных данных:

{
    "properties": {
        "roleDefinitionId": "/subscriptions/{subscriptionId1}/providers/Microsoft.Authorization/roleDefinitions/a795c7a0-d4a2-40c1-ae25-d81f01202912",
        "principalId": "{objectId1}",
        "principalType": "User",
        "scope": "/subscriptions/{subscriptionId1}",
        "condition": null,
        "conditionVersion": null,
        "createdOn": "2022-05-06T23:55:23.7679147Z",
        "updatedOn": "2022-05-06T23:55:23.7679147Z",
        "createdBy": null,
        "updatedBy": "{updatedByObjectId1}",
        "delegatedManagedIdentityResourceId": null,
        "description": null
    },
    "id": "/subscriptions/{subscriptionId1}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentId1}",
    "type": "Microsoft.Authorization/roleAssignments",
    "name": "{roleAssignmentId1}"
}

New service principal

If you create a new service principal and immediately try to assign a role to that service principal, that role assignment can fail in some cases. For example, if you create a new managed identity and then try to assign a role to that service principal, the role assignment might fail. Причина этого сбоя, скорее всего, задержка репликации. The service principal is created in one region; however, the role assignment might occur in a different region that hasn't replicated the service principal yet.

To address this scenario, use the Role Assignments - Create REST API and set the principalType property to ServicePrincipal. You must also set the apiVersion to 2018-09-01-preview or later. 2022-04-01 — первая стабильная версия.

PUT https://management.azure.com/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentId}?api-version=2022-04-01
{
  "properties": {
    "roleDefinitionId": "/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}",
    "principalId": "{principalId}",
    "principalType": "ServicePrincipal"
  }
}

Дальнейшие действия