如何使用图表 api 更新 Azure 广告中的用户密码

How to update the password of user in azure ad using graph api

我正在使用 Microsoft graph API 来更新用户的密码。我有以下 json 请求:

{
    "accountEnabled": true,
    "userPrincipalName": "testuser34@mytenantname.onmicrosoft.com",
    "passwordProfile": {
        "forceChangePasswordNextSignIn": false,
        "password": "<new_password>"
    }
}

我正在使用 PATCH 方法调用此 url https://graph.microsoft.com/v1.0/users/testuser34@mytenantname.onmicrosoft.com。我还将不记名令牌作为授权 header 传递,但出现以下错误:

{
  "error": {
    "code": "Authorization_RequestDenied",
    "message": "Insufficient privileges to complete the operation.",
    "innerError": {
      "request-id": "12781f2a-0cdd-449d-94d7-aae1440a7559",
      "date": "2020-04-03T02:52:57"
    }
  }
}

错误说 Insufficient privileges。根据这个 page 我正在关注,它说:

When updating the passwordProfile property, the following permission is required: Directory.AccessAsUser.All.

我已经在创建的应用程序中检查过了,这个权限在应用程序注册中有

但我仍然收到此错误。任何人都可以帮助解决此错误。谢谢

编辑:在 Microsoft 中也添加了权限,但仍然出现相同的错误

编辑 2:

我从以下代码中获取令牌:

data = {    
            "grant_type": "client_credentials",
            "client_secret": <client_secret>,
            "client_id": <client_id>,
            "resource": "https://graph.microsoft.com"
       }

r = requests.post("https://login.microsoftonline.com/<tennant_id>/oauth2/token", data)

if r.status_code == 200:
    ret_body = r.json()
    token = ret_body['access_token']
else:
    log.error("Unable to get token from oauth {}, {}".format(r.status_code, r.json()))

编辑3:

我在用户管理员中也添加了应用名称:

但问题依旧。

您正在使用 Microsoft Graph,因此您需要在 Microsoft Graph 而不是 Azure Active Directory Graph 中添加权限。

更新:

您使用的是client credentials flow,使用此流程时,需要Application permission,如果要获取令牌更新passwordProfile需要委派权限 Directory.AccessAsUser.All,更新用户Application permission,我们最多可以添加Directory.ReadWrite.All,但是这个权限不能reset user passwords

检查 permissions 从最低到最高特权:

然后查看 Directory.ReadWrite.AllRemarks:

解法:

要使用客户端凭据流更新 passwordProfile,请将 AD 应用程序的服务主体添加为 Azure AD 中的目录角色。

导航到门户中的 Azure Active Directory -> Roles and administrators -> User administrator -> Add assignments -> 搜索您的广告应用程序的名称 -> Add.

然后获取令牌调用API,它工作正常: