【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&$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 环境】用 PowerShell 调用 AAD Token, 以及调用Azure REST API(如资源组列表)
问题描述 PowerShell 脚本调用Azure REST API, 但是所有的API都需要进行权限验证.要在请求的Header部分带上Authorization参数,并用来对List Resour ...
- 【Azure 应用服务】NodeJS Express + MSAL 应用实现AAD登录并获取AccessToken -- cca.acquireTokenByCode(tokenRequest)
问题描述 在上一篇博文 "[Azure 应用服务]NodeJS Express + MSAL 应用实现AAD集成登录并部署在App Service Linux环境中的实现步骤"中, ...
- 【Azure Developer】使用 Microsoft Graph API 获取 AAD User 操作示例
问题描述 查看官方文档" Get a user " , 产生了一个操作示例的想法,在中国区Azure环境中,演示如何获取AAD User信息. 问题解答 使用Microsoft G ...
- AAD Service Principal获取azure user list (Microsoft Graph API)
本段代码是个通用性很强的sample code,不仅能够操作AAD本身,也能通过Azure Service Principal的授权来访问和控制Azure的订阅资源.(Azure某种程度上能看成是两个 ...
- 【Azure Developer】Python代码通过AAD认证访问微软Azure密钥保管库(Azure Key Vault)中机密信息(Secret)
关键字说明 什么是 Azure Active Directory?Azure Active Directory(Azure AD, AAD) 是 Microsoft 的基于云的标识和访问管理服务,可帮 ...
- 【Azure 环境】【Azure Developer】使用Python代码获取Azure 中的资源的Metrics定义及数据
问题描述 使用Python SDK来获取Azure上的各种资源的Metrics的名称以及Metrics Data的示例 问题解答 通过 azure-monitor-query ,可以创建一个 metr ...
- 【Azure Developer】使用 CURL 获取 Key Vault 中 Secrets 中的值
问题描述 在使用CURL通过REST API获取Azure Key Vaualt的Secrets值,提示Missing Token, 问如何来生成正确的Token呢? # curl 命令 curl - ...
- 【Azure 环境】使用Microsoft Graph PS SDK 登录到中国区Azure, 命令Connect-MgGraph -Environment China xxxxxxxxx 遇见登录错误
问题描述 通过PowerShell 连接到Microsoft Graph 中国区Azure,一直出现AADSTS700016错误, 消息显示 the specific application was ...
- Azure DevOps 利用rest api设置variable group
我们在Azure DevOps中设置参数的时候,可以使用build,release各自的variables,但是各自的变量不能共用.此时我们需要使用variable group,它允许跨Build和R ...
- 【Azure 环境】Azure Resource Graph Explorer 中实现动态数组数据转换成多行记录模式 - mv-expand
问题描述 想对Azure中全部VM的NSG资源进行收集,如果只是查看一个VM的NSG设定,可以在门户页面中查看表格模式,但是如果想把导出成表格,可以在Azure Resource Graph Expl ...
随机推荐
- [转帖]CPU Utilization is Wrong
Brendan Gregg's Blog home CPU Utilization is Wrong 09 May 2017 The metric we all use for CPU utiliza ...
- openEuler technical-certification
https://gitee.com/meitingli/technical-certification/ 介绍 存放openEuler技术测评相关的文档,包括技术测评标准.流程.指导性文档等 技术测评 ...
- Whisper对于中文语音识别与转写中文文本优化的实践(Python3.10)
阿里的FunAsr对Whisper中文领域的转写能力造成了一定的挑战,但实际上,Whisper的使用者完全可以针对中文的语音做一些优化的措施,换句话说,Whisper的"默认"形态 ...
- 性能加速包: SpringBoot 2.7&JDK 17,你敢尝一尝吗 | 京东物流技术团队
前言 众所周知,SpringBoot3.0迎来了全面支持JDK17的局面,且最低支持版本就是JDK17,这就意味着,Spring社区将完全抛弃JDK8,全面转战JDK17.作为JAVA开源生态里的扛把 ...
- vue3中beforeRouteEnter 的使用和注意点
beforeRouteEnter 在vue3中的使用 有些时候,我们需要在知道是从哪一个页面过来的. 然后做一些逻辑处理 比如说:从A->B,B页面需要调用接口,回填B页面中的数据 B--> ...
- MyBatis 源码系列:MyBatis 体系结构、六大解析器
体系结构 MyBatis是一个持久层框架,其体系结构分为三层:基础支持层.核心处理层和接口层. 基础支持层包括数据源模块.事务管理模块.缓存模块.Binding模块.反射模块.类型转换模块.日志模块. ...
- MetaGPT( The Multi-Agent Framework):颠覆AI开发的革命性多智能体元编程框架
"MetaGPT( The Multi-Agent Framework):颠覆AI开发的革命性多智能体元编程框架" 一个多智能体元编程框架,给定一行需求,它可以返回产品文档.架构设 ...
- Python中局部放大图案例
例子一: 先上完整代码和效果图: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.ins ...
- tensorflow语法【shape、tf.trainable_variables()、Optimizer.minimize()】
相关文章: [一]tensorflow安装.常用python镜像源.tensorflow 深度学习强化学习教学 [二]tensorflow调试报错.tensorflow 深度学习强化学习教学 [三]t ...
- Java并发编程面试题
Synchronized 用过吗,其原理是什么? Synchronized是jvm实现的一种互斥同步访问方式,底层是基于对象的监视器monitor实现的. 被synchronize修饰的代码在反编译后 ...