首页 > 解决方案 > 使用 Graph API (Azure AD B2C) 更改密码

问题描述

从 Angular 前端和 webapi 作为后端,我正在尝试使用 Graph API 更改密码功能,但出现以下错误:

{"odata.error":{"code":"Authorization_RequestDenied","message":{"lang":"en","value":"修改密码操作被拒绝。"}}}

下面是我的代码:

           private async void ChangePasswordPostRequest(ChangePasswordModel changePasswordModel){
                AuthenticationResult result = await authContext.AcquireTokenAsync(ApplicationConstants.aadGraphResourceId, credential);
                HttpClient http = new HttpClient();
                string url = ApplicationConstants.aadGraphEndpoint + tenant + "/users/" + "c55f7d4d-f81d-4338-bec7-145225366565" + "/changePassword?" + ApplicationConstants.aadGraphVersion;         

                HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("POST"), url);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

                request.Content = new StringContent(JsonConvert.SerializeObject(new ChangePasswordPostModel() { currentPassword = changePasswordModel.CurrentPassword, newPassword = changePasswordModel.NewPassword }), Encoding.UTF8, "application/json");

                HttpResponseMessage response = await http.SendAsync(request);
                if (!response.IsSuccessStatusCode)
                {
                    string error = await response.Content.ReadAsStringAsync();
                    object formatted = JsonConvert.DeserializeObject(error);
                }
            }

我坚持这一点,任何帮助将不胜感激。提前致谢。

标签: azureazure-ad-b2c

解决方案


更改密码操作只能代表已登录用户调用。应用程序可以使用重置密码操作更改用户的密码。必须将应用程序分配给用户帐户管理员角色才能更改用户的密码。@克里斯帕吉特

使用 Graph API 的 beta 端点,现在可以在没有 PowerShell 的情况下完成它!

//Get App ObjectId
https://graph.microsoft.com/beta/servicePrincipals?$filter=appId eq '{appId}'

//Get roleId User Account Administrator role
GET: https://graph.microsoft.com/v1.0/directoryRoles?$filter=roleTemplateId eq 'fe930be7-5e62-47db-91af-98c3a49a38b1'

//If not found //Activate
POST: https://graph.microsoft.com/v1.0/directoryRoles

{
  "displayName": "User Account Administrator",
  "roleTemplateId": "fe930be7-5e62-47db-91af-98c3a49a38b1"
}

//Add member
POST: https://graph.microsoft.com/beta/directoryRoles/{Id}/members/$ref
{
  "@odata.id": "https://graph.microsoft.com/beta/servicePrincipals/{Id returned in first request}"
}

推荐阅读