首页 > 解决方案 > 如何获取当前上下文(登录实体)objectId

问题描述

我正在尝试获取当前(登录的)服务主体\应用程序对象 ID。我的代码:

graphrbac_client = GraphRbacManagementClient(
    credentials = ServicePrincipalCredentials(
        client_id = CLIENT,
        secret = KEY,
        tenant = TENANT_ID,
        resource = "https://graph.windows.net"
    ),
    TENANT_ID
)
for sp in graphrbac_client.service_principals.list():
  if sp.app_id == graphrbac_client.config.credentials.id:
    print('found it')

这有效,但需要太多的应用程序权限(我只设法让它与 Directory.ReadAll 一起使用,不适用于Application.ReadWrite.All,出于某种原因)。我似乎找到的所有方法似乎都需要预先知道 objectId ......这就是我想要检索的。

使用这个

def resolve_service_principal(identifier):
    """Get an object_id from a client_id.
    """
    graphrbac_credentials = ServicePrincipalCredentials(
        client_id=os.environ['AZURE_CLIENT_ID'],
        secret=os.environ['AZURE_CLIENT_SECRET'],
        tenant=os.environ['AZURE_TENANT_ID'],
        resource="https://graph.windows.net"
    )
    graphrbac_client = GraphRbacManagementClient(
        graphrbac_credentials,
        os.environ['AZURE_TENANT_ID']
    )

    result = list(graphrbac_client.service_principals.list(filter="servicePrincipalNames/any(c:c eq '{}')".format(identifier)))
    if result:
        return result[0].object_id
    raise RuntimeError("Unable to get object_id from client_id")

标签: pythonazureazure-active-directorymicrosoft-graph-api

解决方案


您至少需要包 0.50.0 和signed_in_user.get. 当我连接到我的管理员帐户时的示例:

user = graphrbac_client.signed_in_user.get()
assert user.mail_nickname.startswith("admin")

https://docs.microsoft.com/en-us/python/api/azure-graphrbac/azure.graphrbac.operations.signedinuseroperations?view=azure-python#get-custom-headers-none--raw-false-- --操作配置-

(我在这个 SDK 团队的微软工作)

编辑:这似乎只适用于用户,然后我会尝试:

    objects = graphrbac_client.objects.get_objects_by_object_ids({
        'object_ids': [CLIENT],
        'types': ['ServicePrincipal']
    })

推荐阅读