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

AAD ,perform ,to ,operation · 浏览次数 : 5

小编点评

**问题分析:** 在访问 AAD Groups 时,由于权限不足,导致获取 Token 时出现 `UnauthorizedAccessException` 错误。 **解决方案:** 1. **检查权限:** - 使用门户查看应用程序的权限列表,以确定其可以访问的资源。 - 确保应用程序拥有 necessary 的权限以访问 AAD Groups。 2. **获取 AAD 组列表:** - 使用 `list_aad_groups()` 函数获取所有 AAD 组的 ID 和信息。 - 您可以通过查看 AAD 组的活动日志来进一步了解其权限。 3. **下载活动日志:** - 使用 `download_pim_audit_log()` 函数下载每个 AAD 组的活动日志。 - 确保使用正确的凭据和日期范围。 4. **检查日志文件:** - 验证日志文件是否包含您想要访问的活动的信息。 - 如果日志文件无法访问,请确保权限问题或日志文件损坏。 5. **重试获取 Token:** - 确保您拥有正确的信息,例如客户端 ID 和客户端凭据。 - 尝试再次获取 Token,可能需要重新授权。

正文

问题描述

通过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)


 

 

 

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

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

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

【Azure 环境】移动应用 SSO 登录AAD, MSAL的配置为Webview模式时登录页面无法加载

问题描述 移动端集成MASL登录过程中,配置文件中配置项“authorization_user_agent”使用“DEFAULT”可以正常登录,但是改为“WEBVIEW”后就无法登陆,一直处于Loading状态。 参考的示例文档: https://docs.microsoft.com/zh-cn/a

【Azure 环境】使用 az ad group create 时候遇见 Insufficient privileges to complete the operation

问题描述 使用China Azure,通过Azure CLI 创建AAD组报错,提示权限不足 Insufficient privileges to complete the operation # 使用这个登录: az login --service-principal --username xxx

【Azure Developer】使用 Microsoft Graph API 获取 AAD User 操作示例

问题描述 查看官方文档“ Get a user ” , 产生了一个操作示例的想法,在中国区Azure环境中,演示如何获取AAD User信息。 问题解答 使用Microsoft Graph API,演示如何获取AAD User信息,因参考文档是针对Global Azure,所以文档种的URL为: /

【Azure Developer】Go语言调用Azure SDK如何登录到中国区Azure环境

问题描述 在 “使用 Azure SDK for Go 进行 Azure 身份验证” 文章中的 Go 示例代码进行登录Azure时,默认指向的是Globa Azure。当只修改AAD AZURE_CLIENT_ID , AZURE_TENANT_ID 和 AZURE_CLIENT_SECRET参数值

【Azure 环境】使用az login登录遇见OSError: [WinError -2146893813] : '' 错误

az login | Decryption failed:[WinError -2146893813] Key not vaid for use in specified state | msal_extensions.persistence: DPAPI error likely caused by file content not previously encrypted. App dev

【Azure 环境】把OpenSSL生产的自签名证书导入到Azure Key Vault Certificate中报错

问题描述 通过本地生成的自签名证书导入到Azure Key Vault Certificate报错。 错误信息 the specified PEM X.509 certificate content can not be read. Please check if certificate is in

【Azure 环境】Azure 云环境对于OpenSSL 3.x 的严重漏洞(CVE-2022-3602 和 CVE-2022-3786)的处理公告

问题描述 引用报告:(OpenSSL3.x曝出严重漏洞 : https://www.ctocio.com/ccnews/37529.html ) 最近OpenSSL 3.x 爆出了严重安全漏洞,分别是 CVE-2022-3602 和 CVE-2022-3786. CVE-2022-3602 缓冲区溢

【Azure 环境】Azure 流分析服务(Steam Analytics) 报出 OutputDataConversionError 错误引起延迟及超时

问题描述 Azure 流分析服务(Steam Analytics) 报出 OutputDataConversionError 错误引起延迟及超时。 查看详细错误: 问题解答 在错误消息中,有非常明确的提示:Cannot write event(s) to SQL Database due to is

【Azure 环境】向Azure Key Vault中导入证书有输入密码,那么导出pfx证书的时候,为什么没有密码呢?

问题描述 将pfx证书导入Key Vault的证书时,这个PFX需要输入正确的密码导入成功。但是当需要导出时,生成的pfx证书则不需要密码。这是正常的情况吗? 问题解答 是的,这是Azure Key Vault 证书导入/导出 功能的设计使然。当一个PFX不需要密码的时候,也可以直接导入到Azure