首页 > 解决方案 > Azure 使用 Python 添加应用程序角色分配

问题描述

我正在尝试使用 Python 通过 Graph API 向 Azure AD 用户添加新的应用程序角色。但我面临问题。我遵循微软文档:https ://docs.microsoft.com/en-us/graph/api/user-post-approleassignments?view=graph-rest-1.0&tabs=http

使用 Postman 时,该结构可以正常工作。下面是 Python 脚本:

import json, requests

def test():
    token={ACCESS_TOCKEN}
    data={"principalId":"ff868303-fbb7-4027-87a1-00b92013d343","resourceId":"4f162966-2c98-4439-b924-7730c40e98551","appRoleId":"827ee854-4907-4e96-b238-c861d846c450"}
    return requests.post('https://graph.microsoft.com/v1.0/Users/ff868303-fbb7-4027-87a1-00b92013d343/appRoleAssignments',
    headers={'Authorization': 'Bearer ' + token_request , 'Content-Type': "application/json"},
    data=data
    )

错误:

{'error': {'code': 'BadRequest', 'message': 'Unable to read JSON request payload. Please ensure Content-Type header is set and payload is of valid JSON format.', 'innerError': {'date': '2020-11-25T15:43:24', 'request-id': 
'8301f593-cab8-4228-b053-c9d24139a85f', 'client-request-id': '8301f593-cab8-4228-b053-c9d24139a85f'}}}

标签: pythonazureapipython-requestsazure-active-directory

解决方案


因为您没有将 json 发布到 REST API。使用 'json' 参数而不是 post 方法的 'data'。请参阅https://requests.readthedocs.io/en/master/user/quickstart/#more-complicated-post-requests。应该:

import json, requests
from uuid import UUID

def test():
    token={ACCESS_TOCKEN}
    data={"principalId":UUID("ff868303-fbb7-4027-87a1-00b92013d343"),"resourceId":UUID("4f162966-2c98-4439-b924-7730c40e98551"),"appRoleId":UUID("827ee854-4907-4e96-b238-c861d846c450")}
    return requests.post('https://graph.microsoft.com/v1.0/Users/ff868303-fbb7-4027-87a1-00b92013d343/appRoleAssignments',
    headers={'Authorization': 'Bearer ' + token, 'Content-Type': "application/json"},
    json = data
    )

或者,您也可以从字典中转储 json 并传入 data 参数。data = json.dumps(data).


推荐阅读