首页 > 解决方案 > 更改用户密码以使用 Azure Graph API

问题描述

我无法更改已登录 Azure AD B2C 用户的密码。我有用于开发和 QA 的 Azure B2C 租户。另外,我有两个应用程序 something-Local 和 something-QA,分别用于 Azure B2C 中的 DEV 和 QA,如下所示,我已经验证了它们的两个应用程序的设置是相同在此处输入图像描述 下面是应用程序的配置 这是我用于 B2C 连接的代码

 private OpenIdConnectAuthenticationOptions CreateOptionsFromPolicy(string policy)
    {
        return new OpenIdConnectAuthenticationOptions
        {
            // For each policy, give OWIN the policy-specific metadata address, and
            // set the authentication type to the id of the policy
            // meta data
            MetadataAddress = "https://login.microsoftonline.com/" + "mytenant" + "/v2.0/.well-known/openid-configuration?p=" + policy,
            AuthenticationType = policy,

            // These are standard OpenID Connect parameters, with values pulled from web.config
            ClientId = AzureAdConfig.ClientId,
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                AuthorizationCodeReceived = OnAuthorizationCodeReceived,
                AuthenticationFailed = OnAuthenticationFailed,
                SecurityTokenValidated = OnSecurityTokenValidated,
                RedirectToIdentityProvider = OnRedirectToIdentityProvider,
            },
            Scope = "openid",
            ResponseType = "id_token",

            // This piece is optional - it is used for displaying the user's name in the navigation bar.
            TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = "name",
            }
        };
    }

在上面的代码中,用于 QA 和 Dev 的 ClientID 是不同的。 下面是用于使用图形 API 更改用户密码的代码。

 public async Task<HttpResponseMessage> ChangePassword(string currentPassword, string newPassword)
    {
        string userId = ClaimValues.ObjectIdentifier();
        var adUser = _activeDirectoryClient.Users
            .Where(u => u.ObjectId.Equals(userId))
            .ExecuteAsync().Result.CurrentPage.FirstOrDefault();

        string upn = adUser.UserPrincipalName;
        var client = new HttpClient();
        string uriString = "https://login.microsoftonline.com/"+ AzureAdConfig.Tenant + "/oauth2/token";
        Uri requestUri = new Uri(uriString);
        string requestString = "resource=https%3a%2f%2fgraph.windows.net&client_id=" + AzureAdConfig.AppId + "&grant_type=password&username=" + upn + "&password=" + currentPassword + "&client_secret=" + AzureAdConfig.AppKey;
        var tokenResult = await client.PostAsync(requestUri, new StringContent(requestString, Encoding.UTF8, "application/x-www-form-urlencoded"));
        if (tokenResult.IsSuccessStatusCode)
        {
            var stringResult = await tokenResult.Content.ReadAsStringAsync();
            GraphApiTokenResult objectResult = JsonConvert.DeserializeObject<GraphApiTokenResult>(stringResult);
            client = new HttpClient();
            string requestUrl = AzureAdConfig.GraphResourceId + AzureAdConfig.Tenant + "/me/changePassword?" + AzureAdConfig.GraphVersion;
            Uri graphUri = new Uri(requestUrl);
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", objectResult.access_token);
            requestString = JsonConvert.SerializeObject(new
            {
                currentPassword = currentPassword,
                newPassword = newPassword
            });
            var response = await client.PostAsync(graphUri, new StringContent(requestString, Encoding.UTF8, "application/json"));
            return response;
        }
        else
        {
            return tokenResult;
        }
    }

另外,我想了解 Azure Active Directory 服务中的应用程序注册和 Azure AD B2C 中的应用程序有什么区别?

提前致谢

标签: azure-active-directoryazure-ad-b2cazure-ad-graph-api

解决方案


要使用 Azure AD Graph API 更改用户密码,首先您应该是租户中的全局管理员,然后您可以使用PATCH https://graph.windows.net/myorganization/users/{user_id}?api-version并更新。

    {
  "passwordProfile": {
    "password": "value",
    "forceChangePasswordNextLogin": false
  }
}

另外,我想了解 Azure Active Directory 服务中的应用程序注册和 Azure AD B2C 中的应用程序有什么区别?

您可以从此处了解 Azure AD 租户和 Azure AD B2C 租户之间的区别。

希望它可以帮助你。


推荐阅读