问题描述

通过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 错误的更多相关文章

  1. 【Azure 环境】用 PowerShell 调用 AAD Token, 以及调用Azure REST API(如资源组列表)

    问题描述 PowerShell 脚本调用Azure REST API, 但是所有的API都需要进行权限验证.要在请求的Header部分带上Authorization参数,并用来对List Resour ...

  2. 【Azure 应用服务】NodeJS Express + MSAL 应用实现AAD登录并获取AccessToken -- cca.acquireTokenByCode(tokenRequest)

    问题描述 在上一篇博文 "[Azure 应用服务]NodeJS Express + MSAL 应用实现AAD集成登录并部署在App Service Linux环境中的实现步骤"中, ...

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

    问题描述 查看官方文档" Get a user " , 产生了一个操作示例的想法,在中国区Azure环境中,演示如何获取AAD User信息. 问题解答 使用Microsoft G ...

  4. AAD Service Principal获取azure user list (Microsoft Graph API)

    本段代码是个通用性很强的sample code,不仅能够操作AAD本身,也能通过Azure Service Principal的授权来访问和控制Azure的订阅资源.(Azure某种程度上能看成是两个 ...

  5. 【Azure Developer】Python代码通过AAD认证访问微软Azure密钥保管库(Azure Key Vault)中机密信息(Secret)

    关键字说明 什么是 Azure Active Directory?Azure Active Directory(Azure AD, AAD) 是 Microsoft 的基于云的标识和访问管理服务,可帮 ...

  6. 【Azure 环境】【Azure Developer】使用Python代码获取Azure 中的资源的Metrics定义及数据

    问题描述 使用Python SDK来获取Azure上的各种资源的Metrics的名称以及Metrics Data的示例 问题解答 通过 azure-monitor-query ,可以创建一个 metr ...

  7. 【Azure Developer】使用 CURL 获取 Key Vault 中 Secrets 中的值

    问题描述 在使用CURL通过REST API获取Azure Key Vaualt的Secrets值,提示Missing Token, 问如何来生成正确的Token呢? # curl 命令 curl - ...

  8. 【Azure 环境】使用Microsoft Graph PS SDK 登录到中国区Azure, 命令Connect-MgGraph -Environment China xxxxxxxxx 遇见登录错误

    问题描述 通过PowerShell 连接到Microsoft Graph 中国区Azure,一直出现AADSTS700016错误, 消息显示 the specific application was ...

  9. Azure DevOps 利用rest api设置variable group

    我们在Azure DevOps中设置参数的时候,可以使用build,release各自的variables,但是各自的变量不能共用.此时我们需要使用variable group,它允许跨Build和R ...

  10. 【Azure 环境】Azure Resource Graph Explorer 中实现动态数组数据转换成多行记录模式 - mv-expand

    问题描述 想对Azure中全部VM的NSG资源进行收集,如果只是查看一个VM的NSG设定,可以在门户页面中查看表格模式,但是如果想把导出成表格,可以在Azure Resource Graph Expl ...

随机推荐

  1. 给无网络的CentOS服务器下载rpm包的一个解决办法

    很多公司的服务器为了安全都在内网, 是无法直接连接互联网的, 无法连接互联网就无法使用yum等的包管理器安装rpm包等. 有时候一些rpm包还是能很好的提高性能的, 所以可以使用多种方式获取rpm包进 ...

  2. vue 路由守卫是否携带token

    //整个实例出来 配置路由守卫 const router = new Router({ //这里面是路由配置哈 }) router.beforeEach((to, from, next) => ...

  3. 大数据面试题集锦-Hadoop面试题(二)-HDFS

    你准备好面试了吗?这里有一些面试中可能会问到的问题以及相对应的答案.如果你需要更多的面试经验和面试题,关注一下"张飞的猪大数据分享"吧,公众号会不定时的分享相关的知识和资料. 目录 ...

  4. SqlSugar Code First

      注意点 1.SqlSugar Code First可以快速开发,使用起来也要分阶段使用,比如早期随便搞,中后期需要禁用一些功能保证数据安全(标题6和7 ) 2.数据库账号需要有比较高的权限, 3. ...

  5. pthread库的使用

    目录 1.说明 2.使用 2.1.pthread_create 2.2.pthread_join 2.3.pthread_exit 2.4.pthread_self 2.5.pthraad_detac ...

  6. 官方实锤!AMD真的已经有了大小核:不搞Intel那一套

    Intel 12代酷睿开始引入大小核混合架构,多核跑分提升立竿见影,在游戏.渲染等场景中也有很好的辅助作用,但因为大核心.小核心基于完全不同的架构,需要复杂的系统.软件调度配合,也直接导致失去了AVX ...

  7. 捉虫日记:使用OpenGL加载模型 (2023/12/11)

      前天晚上,花了一个小时解决了编译Assimp时的报错问题,顺便写了篇随笔.今天继续OpenGL的学习,不出意料地再次踩坑,好在最后都解决了.   今天主要学习使用Assimp加载模型,原理很简单: ...

  8. 使用Visual studio code 进行.NET 开发

    Visual studio code 作为一款强大的编辑器,相信很多开发者都用过.vs code 的强大源自开源生态丰富,编辑器本身简单,但是加上各式的插件,就变得无比牛逼,基本可以替代现有的大部分工 ...

  9. Oracle 19c RAC自动应用RU补丁过程

    笔者好久没有使用opatchauto打过补丁了,搜了下自己的历史随笔,上次opatchauto打补丁的记录还是Oracle 11g版本: Oracle 11g RAC 自动应用PSU补丁简明版 而11 ...

  10. DNS子域委派配置·

    实验介绍:DNS子域委派的作用 子域即为主域下的一个子域名,当一个子域的流量过大时,主域的DNS服务器可以把一个子域的查询授权给一台专门的子域服务器 注意被委派的服务器必须是委派服务器的子域服务器. ...