【Azure 环境】AAD 注册应用获取AAD Group权限接口遇 403 : Attempted to perform an unauthorized operation 错误

发布时间 2023-07-26 21:15:10作者: 路边两盏灯

问题描述

通过Azure AD的注册应用获取到Token后,访问AAD Group并查看日志信息时候,遇见了 {"error":{"code":"UnauthorizedAccessException","message":"Attempted to perform an unauthorized operation."}}

Python 代码 -- 使用AAD 注册应用获取Token

import requests
import json

def get_bearer_token():
    tenant_id = "your azure tenant id"
    client_id = "your AAD registrations application id "
    client_secret = "***********************************"

    # The resource (URI) that the bearer token will grant access to
    scope = 'https://api.azrbac.azurepim.identitygovernance.azure.cn/.default'
    # Azure AD authentication endpoint
    AUTHORITY = f'https://login.chinacloudapi.cn/{tenant_id}/oauth2/v2.0/token'
    # Request an access token from Azure AD
    response = requests.post(
        AUTHORITY,
        data={
            'grant_type': 'client_credentials',
            'client_id': client_id,
            'client_secret': client_secret,
            'scope': scope
        }
    )

    if response.status_code == 200:
        access_token = response.json().get('access_token')
    else:
        print("Error occurred while retrieving token:", response.text)
    return access_token

但是,在调用 https://api.azrbac.azurepim.identitygovernance.azure.cn/api/v2/privilegedAccess/aadGroups/activities 接口时候,遇见错误,提示权限不够。

  {"error":{"code":"UnauthorizedAccessException","message":"Attempted to perform an unauthorized operation."}}

 

问题解答

因错误消息提示当前 Access Token无权查看AAD Groups的Activities日志,所以需要进入具体的AAD Groups查看,当前AAD注册应用是否由权限进行任何操作。 如无,加入权限后就可以解决问题(PS: 赋予Member 或 Owner权限都可以)

 

在门户上直接查看的方式:

门户入口:https://portal.azure.cn/#view/Microsoft_Azure_PIMCommon/CommonMenuBlade/~/aadgroup

通过API来列出权限操作列表:

url = "https://api.azrbac.azurepim.identitygovernance.azure.cn/api/v2/privilegedAccess/aadGroups/resources/"+str(aad_groups_list[index]['id'])+"/permissions"

将应用程序加入active assignment后即可获得权限

{'accessLevel': 'AdminRead', 'isActive': True, 'isEligible': False}, {'accessLevel': 'ActivityRead', 'isActive': True, 'isEligible': False}

 

附录:根据AAD Token获取AAD Group列表和每一个AAD Group的Activity Logs



import requests
import json


def get_bearer_token():
tenant_id = "your azure tenant id"

client_id = "your AAD registrations application id "


client_secret = "***********************************"


# The resource (URI) that the bearer token will grant access to
scope = 'https://api.azrbac.azurepim.identitygovernance.azure.cn/.default'


# Azure AD authentication endpoint
AUTHORITY = f'https://login.chinacloudapi.cn/{tenant_id}/oauth2/v2.0/token'


# Request an access token from Azure AD
response = requests.post(
AUTHORITY,
data={
'grant_type': 'client_credentials',
'client_id': client_id,
'client_secret': client_secret,
'scope': scope
}
)


if response.status_code == 200:
access_token = response.json().get('access_token')
else:
print("Error occurred while retrieving token:", response.text)


return access_token


def list_aad_groups(bearer_token):
url = https://api.azrbac.azurepim.identitygovernance.azure.cn/api/v2/privilegedAccess/aadGroups/resources?$select=id,displayName,type,externalId&$expand=parent


headers = {
'Authorization': bearer_token
}


response = requests.get(url=url,headers=headers)


data = json.loads(response.text)


aad_groups_count = data["value"].__len__()


aad_groups_list = []


for aad_groups_index in range(0,aad_groups_count):
aad_groups = {}
aad_groups["id"] = data["value"][aad_groups_index]["id"]
aad_groups["name"] = data["value"][aad_groups_index]["displayName"]
aad_groups_list.append(aad_groups)


return aad_groups_list


def download_pim_audit_log(date, group_id, group_name, bearer_token):


start_time = str(date) + "T00:00:00.000Z"
end_time = str(date) + "T23:59:59.999Z"


url = https://api.azrbac.azurepim.identitygovernance.azure.cn/api/v2/privilegedAccess/aadGroups/activities?$filter=createdDateTime+ge+ + str(start_time) + "+and+createdDateTime+le+" + str(end_time) + "+and+resource/id+eq+%27" + str(group_id) + "%27&$orderby=createdDateTime+desc&$expand=requestor,originalRequestor,subject,target,resource($expand=parent),scopedResource"


headers = {
'Authorization': bearer_token
}



response = requests.get(url=url, headers=headers)


if response.status_code == 200:
raw_data = json.loads(response.text)


data = raw_data["value"]


records_count = data.__len__()


dst_path = "\\" + str(date) + " " + str(group_name) + ".json"
file_debug = open(dst_path, "a+")


for record_index in range(0, records_count):
record = str(data[record_index]).replace("None","'None'")
file_debug.write(record)
file_debug.write("\n")


return True


else:
print("Failed to Download log : " + response.text)
exit()


if __name__ == '__main__':


token = "Bearer " + str(get_bearer_token())


print(token)


date = "2023-07-26"


aad_groups_list = list_aad_groups(token)


for index in range(0,aad_groups_list.__len__()):


group_id = aad_groups_list[index]['id']
group_name = aad_groups_list[index]['name']


download_pim_audit_log(date, group_id, group_name, token)