【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?
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?
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)
当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2022-07-26 【Azure 应用服务】PHP应用部署在App Service for Linux环境中,上传文件大于1MB时,遇见了413 Request Entity Too Large 错误的解决方法
2021-07-26 【Azure 应用服务】App Service服务无法启动,打开Kudu站点,App Service Editor 页面均抛出:The service is unavailable