【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 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&select=id,displayName,type,externalId&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?������=���������������+��++���(���������)+"+���+���������������+��+"+���(�������)+"+���+��������/��+��+orderby=createdDateTime+desc&������=���������,�����������������,�������,������,��������(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)
相关文章
|
2月前
|
Windows
【Azure 环境】使用 az ad group create 时候遇见 Insufficient privileges to complete the operation
【Azure 环境】使用 az ad group create 时候遇见 Insufficient privileges to complete the operation
|
2月前
|
API Python
【Azure Developer】AAD API如何获取用户“Block sign in”信息(accountEnabled)
【Azure Developer】AAD API如何获取用户“Block sign in”信息(accountEnabled)
|
13天前
【APIM】启用APIM Analytics时遇见Request failed错误
Data collection is required for detailed monitoring, custom dashboards, and more. A Log Analytics workspace is also required for the data storage. You can change the workspace destination at any time in Diagnostic settings. How do I use Log Analytics?
42 12
|
2月前
|
Java API
【Azure Developer】使用Microsoft Graph API创建用户时候遇见“401 : Unauthorized”“403 : Forbidden”
【Azure Developer】使用Microsoft Graph API创建用户时候遇见“401 : Unauthorized”“403 : Forbidden”
【Azure Developer】使用Microsoft Graph API创建用户时候遇见“401 : Unauthorized”“403 : Forbidden”
|
2月前
|
API
【Azure APIM】调用APIM的备份接口时候遇见Authentication Failed错误
【Azure APIM】调用APIM的备份接口时候遇见Authentication Failed错误
|
2月前
|
存储 API 网络安全
【Azure APIM】调用APIM的备份接口时候遇见InvalidParameters错误
【Azure APIM】调用APIM的备份接口时候遇见InvalidParameters错误
|
2月前
|
存储 网络安全 数据中心
【Azure 存储服务】App Service 访问开启防火墙的存储账号时遇见 403 (This request is not authorized to perform this operation.)
【Azure 存储服务】App Service 访问开启防火墙的存储账号时遇见 403 (This request is not authorized to perform this operation.)
【Azure 存储服务】App Service 访问开启防火墙的存储账号时遇见 403 (This request is not authorized to perform this operation.)
|
2月前
|
API
【Azure API 管理】解决API Management添加AAD Group时遇见的 Failed to query Azure Active Directory graph due to error 错误
【Azure API 管理】解决API Management添加AAD Group时遇见的 Failed to query Azure Active Directory graph due to error 错误
|
2月前
|
IDE Java 开发工具
【Azure Developer】使用Key Vault的过程中遇见的AAD 认证错误
【Azure Developer】使用Key Vault的过程中遇见的AAD 认证错误
|
2月前
|
JSON API 网络架构
【Azure APIM】验证APIM删除后的恢复步骤
【Azure APIM】验证APIM删除后的恢复步骤