更改使用Azure Graph API的用户密码

时间:2018-08-07 22:08:18

标签: azure-active-directory azure-ad-b2c azure-ad-graph-api

我无法更改登录的Azure AD B2C用户的密码。 我有用于开发和QA的Azure B2C租户。此外,我在Azure B2C中分别有两个应用程序something-Local和something-QA分别用于DEV和QA,如下所示,我已经验证了这两个应用程序的设置相同的enter image description here 以下是应用程序的配置 这是我用于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",
            }
        };
    }

在上面的代码中,用于质量检查和开发的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的Azure Active Directory服务中的应用程序注册和Azure的Azure AD B2C中的应用程序之间有什么区别?

预先感谢

1 个答案:

答案 0 :(得分:0)

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

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

我还想了解两者之间的区别   Azure的Azure Active Directory服务中的应用程序注册   以及Azure的Azure AD B2C中的应用程序?

您可以从here中的Azure AD租户与Azure AD B2C租户之间的区别中了解这一点。

希望它可以为您提供帮助。