首页 > 其他分享 >【Azure 环境】AAD 注册应用获取AAD Group权限接口遇 403 : Attempted to perform an unauthorized operation 错误

【Azure 环境】AAD 注册应用获取AAD Group权限接口遇 403 : Attempted to perform an unauthorized operation 错误

时间:2023-07-26 21:23:08浏览次数:49  
标签:AAD Group unauthorized aad response token groups id

问题描述

通过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)


 

 

 

标签:AAD,Group,unauthorized,aad,response,token,groups,id
From: https://www.cnblogs.com/lulight/p/17583555.html

相关文章

  • openGauss学习笔记-21 openGauss 简单数据管理-GROUP BY子句
    openGauss学习笔记-21openGauss简单数据管理-GROUPBY子句GROUPBY语句和SELECT语句一起使用,用来对相同的数据进行分组。您可以对一列或者多列进行分组,但是被分组的列必须存在。21.1语法格式SELECT{*|[column,...]}[FROMfrom_item[,...]][WHEREcondition][......
  • 【项目实战】Kafka 重平衡 Consumer Group Rebalance 机制
    ......
  • MySQL group by分组后,将每组所得到的id拼接起来
    背景需要将商品表中的sku按照spu_id分组后,并且得到每个spu下的sku_id,需要使用到group_concat函数selectspu_id,count(*),group_concat(idSEPARATOR',')asidsfromproduct_skuwherecategory='tv'groupbyspu_id;group_concat函数group_concat函数,实现分组查......
  • var js_usergroup_name python
    如何实现“varjs_usergroup_namepython”作为一名经验丰富的开发者,我很乐意教会刚入行的小白如何实现“varjs_usergroup_namepython”。在这篇文章中,我将为你展示整个实现过程,并提供每个步骤所需的代码和相应的注释。让我们开始吧!实现流程为了更好地理解整个实现过程,我将使......
  • How to Restore ASM Based OCR After Complete Loss of the CRS Diskgroup on Linux/U
    InthisDocumentGoalSolutionReferencesAPPLIESTO:OracleDatabase-EnterpriseEdition-Version11.2.0.1.0andlaterOracleDatabaseCloudSchemaService-VersionN/AandlaterGen1ExadataCloudatCustomer(OracleExadataDatabaseCloudMachine)......
  • 【项目实战】Kafka 重平衡 Consumer Group Rebalance 机制
    ......
  • Python报错 | AttributeError: 'NoneType' object has no attribute 'group'
    报错信息使用Python正则匹配的时候,报如下错误:AttributeError:'NoneType'objecthasnoattribute'group'错误原因报错翻译过来是:属性错误:“NoneType”对象没有属性“group”没有匹配到符合正则表达式的内容,但又调用了group方法。importrestr='hellopython!!!hel......
  • MySQL——GROUP BY详解与优化
    在MySQL中,GROUPBY用于将具有指定列中相同值的行分组在一起。这是在处理大量数据时非常有用的功能,允许对数据进行分类和聚合。基本使用语法以下是GROUPBY子句的基本语法:"""SELECTcol1,col2,...,aggregate_function(col_name)FROMtable_nameWHEREconditionGROUP......
  • MySQL优化之group by
    MySQL之groupbygroupby优化 #删除掉目前的联合索引idx_user_pro_age_sta dropindexidx_user_ro_age_staontb_user; #执行分组操作,根据profession字段分组 explainselectprofession,count(*)fromtb_usergroupbyprofession; #创建索引 Createindexid......
  • Unity UGUI的VerticalLayoutGroup(垂直布局)组件的介绍及使用
    UnityUGUI的VerticalLayoutGroup(垂直布局)组件的介绍及使用1.什么是VerticalLayoutGroup组件?VerticalLayoutGroup是UnityUGUI中的一种布局组件,用于在垂直方向上自动排列子对象。它可以根据子对象的大小和布局设置,自动调整子对象的位置和大小,实现垂直布局效果。2.VerticalLay......