【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 ...
随机推荐
- Java单元测试浅析(JUnit+Mockito)
作者:京东物流 秦彪 1. 什么是单元测试 (1)单元测试环节: 测试过程按照阶段划分分为:单元测试.集成测试.系统测试.验收测试等.相关含义如下: 1) 单元测试: 针对计算机程序模块进 ...
- 【杂题,树】【Uoj】Uoj618 【JOISC2021】聚会 2
2023.7.3 Problem Link 给定一棵 \(n\) 个点的树,对于一个点集 \(S\),定义 \(f(u,S)\) 为 \(\min_u \sum_{v\in S} \mathrm{di ...
- vue数据不响应,可能是用法有问题
<template> <div> <div> <span>用户名: {{ userInfo.name }}</span> <span& ...
- 数组查询includes
let arr1 = ['kk', 'jo', 'll']; if (arr1.includes("kk")) {//[ɪnˈkluːz] console.log("找到 ...
- Go基础之指针
Go语言中的指针 目录 Go语言中的指针 一.Go语言中的指针介绍 1.1 指针介绍 1.2 基本语法 1.3 声明和初始化 1.4 Go 指针的3个重要概念 1.4.1 指针地址(Pointer A ...
- windbg-windows调试工具来抓端游crash dump
windbg下载有两种方式: Install WinDbg - Windows drivers | Microsoft Learn 从微软应用商店下载 dump上的windows的局部变量解析部分进行 ...
- 全新Self-RAG框架亮相,自适应检索增强助力超越ChatGPT与Llama2,提升事实性与引用准确性
全新Self-RAG框架亮相,自适应检索增强助力超越ChatGPT与Llama2,提升事实性与引用准确性 1. 基本思想 大型语言模型(LLMs)具有出色的能力,但由于完全依赖其内部的参数化知识,它们 ...
- 用上了Jenkins,个人部署项目真方便!
作者:小傅哥 博客:https://bugstack.cn 项目:https://gaga.plus 沉淀.分享.成长,让自己和他人都能有所收获! 本文的宗旨在于通过简单干净实践的方式教会读者,如何在 ...
- 营销(marketing)、推广(Promotion)和 运营(Operation)的概念分别是什么?
首先要明确的原则: 1.你得承认"讨论任何事情之前不弄清楚概念定义就是耍流氓" 2.你得承认"由于每个人的经验学识和理解力的不同,我们常对概念定义产生分歧" 3 ...
- spring cloud与加密库jasypt(ulisesbocchio)冲突问题定位
背景 最近在项目上遇到个问题.项目就是普通的spring cloud,spring cloud在spring boot的基础上多了一些东西,比如支持bootstrap上下文(通过bootstrap.y ...