如何使用 api 或如何使用订阅对象将订阅的贡献者角色分配给服务主体

How to assign a contributor role of subcription to a serviceprincipal using api or how to use subscription object

我尝试使用 api 将订阅的贡献者角色分配给 serviceprincipal。 信息如下:
订阅 ID:b59c6b1b-xxxxxxxxxx
服务主体ID:73eb9e1e-xxxxxxxx
contributor ID: b24988ac-6180-42a0-ab88-20f7382dd24c(Azure内置contributor role ID,我通过azcli.Is得到use 'az role definition list --query "[].{name:name, roleType:roleType, roleName:roleName}" --output tsv'对吧?)

我是这样用的api

POST https://graph.microsoft.com/v1.0/servicePrincipals/b59c6b1b-xxxxxxxxxx/appRoleAssignedTo
Content-Type: application/json
Content-Length: 110

{
  "principalId": "73eb9e1e-xxxxxxxx",
  "resourceId": "b59c6b1b-xxxxxxxxxx",
  "appRoleId": "b24988ac-6180-42a0-ab88-20f7382dd24c"
}

但是我得到了这样的错误响应

{
    "error": {
        "code": "Request_ResourceNotFound",
        "innerError": {
            "client-request-id": "4fed54c4-xxxxxxxxx",
            "date": "2021-01-11T12:00:08",
            "request-id": "4fed54c4-xxxxxxxxx"
        },
        "message": "Resource \u0027b59c6b1b-xxxxxxxxxxx\u0027 does not exist or one of its queried reference-property objects are not present."
    }
}

这意味着订阅没有通过ID找到,在这个例子中,我使用订阅ID,我想可能我应该像其他示例资源一样使用订阅ObjectID。但是我没有找到获取订阅的方法使用门户或 api 的 ObjectID。或者也许我将错误信息修复到 resourceID.So 我想知道我需要知道什么信息才能将订阅的贡献者角色分配给 serviceprincipal

POST https://graph.microsoft.com/v1.0/servicePrincipals/{id}/appRoleAssignedTo
Content-Type: application/json
Content-Length: 110

{
  "principalId": "principalId-value",
  "resourceId": "resourceId-value",
  "appRoleId": "appRoleId-value"
}

这里的{id}和“resourceId”是服务主体的对象id。

您可以通过以下两种方式之一获取此信息:

选项 1:

来自门户:

Azure Active Directory >> 应用注册 >> Select 下拉菜单中的所有应用 >> 找到您的应用并单击它。

选项 2:

来自图表

使用GET /servicePrincipals

https://graph.microsoft.com/beta/serviceprincipals?$filter=startswith(displayName, 'Application-Name')

您必须替换上面的应用程序名称。 上述请求的输出将在 id 键下具有 guid 值。

你用错了API,这个MS Graph API is to assign AAD App role to the service principal, what you need is to assign the RBAC role to the service principal in the subscription, you need to use this API - Role Assignments - Create,你可以点击本页的Try it按钮,登录你的账户直接试试

确保您用来获取令牌的 client/user 具有创建角色分配的权限 Microsoft.Authorization/roleAssignments/write,例如User Access AdministratorOwner.

样本:

PUT https://management.azure.com/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentId}?api-version=2015-07-01

{
  "properties": {
    "roleDefinitionId": "/subscriptions/xxxxx/providers/Microsoft.Authorization/roleDefinitions/de139f84-1756-47ae-9be6-808fbbe84772",
    "principalId": "xxxxxxx"
  }
}

有关详细信息,请按照此 doc 中的每个步骤操作。

此外,如果您可以接受使用 Azure CLI,则可以使用此命令 az role assignment create