Change Password using Microsoft Graph Beta

JS Arya 46 Reputation points
2022-06-06T10:43:37.693+00:00

I am using Microsoft Graph beta and trying to reset password for the user..

It is giving me following error

"Exception of type 'Microsoft.Graph.Beta.Models.ODataErrors.ODataError' was thrown.:::: at Microsoft.Kiota.Http.HttpClientLibrary.HttpClientRequestAdapter.ThrowFailedResponse(HttpResponseMessage response, Dictionary2 errorMapping) at Microsoft.Kiota.Http.HttpClientLibrary.HttpClientRequestAdapter.SendAsync[ModelType](RequestInformation requestInfo, ParsableFactory1 factory, IResponseHandler responseHandler, Dictionary`2 errorMapping, CancellationToken cancellationToken)"

My Code

GraphServiceClient _graphClient = GraphHelper.GetAuthenticatedGraphClient(config, credentials);

            try
            {


                await _graphClient.Users[userId].ChangePassword.PostAsync(new Microsoft.Graph.Beta.Users.Item.ChangePassword.ChangePasswordPostRequestBody
                {
                    CurrentPassword = "Password1",
                    NewPassword = "Password2"
                });
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message + "::::" + ex.StackTrace);
            }

public static GraphServiceClient GetAuthenticatedGraphClient(IConfigurationRoot config, B2CCredentials credentials)
        {

            var scopes = new[] { "https://graph.microsoft.com/.default" };

            var options = new TokenCredentialOptions
            {
                AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
            };


            var clientSecretCredential = new ClientSecretCredential(
                credentials.B2CTenantId, credentials.ClientId, credentials.ClientSecret, options);

            var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

            return graphClient;
        }
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,570 questions
Microsoft Entra External ID
Microsoft Entra External ID
A modern identity solution for securing access to customer, citizen and partner-facing apps and services. It is the converged platform of Azure AD External Identities B2B and B2C. Replaces Azure Active Directory External Identities.
2,639 questions
0 comments No comments
{count} votes

Accepted answer
  1. CarlZhao-MSFT 36,891 Reputation points
    2022-06-07T08:17:43.33+00:00

    Hi @JS Arya

    Only Directory.AccessAsUser.All delegated permissions can change user passwords, refer to the api documentation.

    By the way, since Azure AD B2C's token does not yet support calling graph api, you need to use the Azure AD based authentication flow to authenticate your B2C user and get the token.
    E.g. auth code flow or ROPC flow.

    using Microsoft.Graph;  
    using Azure.Identity;  
      
    namespace test1  
      
    {  
        class Program  
        {  
            static async System.Threading.Tasks.Task Main(string[] args)  
      
            {  
      
                var scopes = new[] { "Directory.AccessAsUser.All" };  
      
                // Multi-tenant apps can use "common",  
                // single-tenant apps must use the tenant ID from the Azure portal  
                var tenantId = "b2c tenant id";  
      
                // Value from app registration  
                var clientId = "b2c app client id";  
      
      
                // using Azure.Identity;  
                var options = new TokenCredentialOptions  
                {  
                    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud  
                };  
      
                var userName = "b2c user name";  
                var password = "password";  
          
                // https://learn.microsoft.com/dotnet/api/azure.identity.usernamepasswordcredential  
                var userNamePasswordCredential = new UsernamePasswordCredential(  
                    userName, password, tenantId, clientId, options);  
      
                var graphClient = new GraphServiceClient(userNamePasswordCredential, scopes);  
      
                var user = new User  
                {  
                    PasswordProfile = new PasswordProfile  
                    {  
                        ForceChangePasswordNextSignIn = false,  
                        Password = "xWwvJ]6NMw+bWH-d"  
                    }  
                };  
      
                await graphClient.Users["user id"]  
                    .Request()  
                    .UpdateAsync(user);  
      
            }  
        }  
    }  
    

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


2 additional answers

Sort by: Most helpful
  1. Shweta Mathur 27,381 Reputation points Microsoft Employee
    2022-06-06T11:55:05.867+00:00

    Hi @JS Arya ,

    Thanks for reaching out.

    Unfortunately, B2C applications do not support graph operations. If you have registered your application in B2C tenant to authenticate with user flow, you won't be able to call Microsoft graph API endpoint.

    B2C application won't allow to add permission of your application which is required to call Graph API endpoints. It allows only "openid" and "offline_access" permissions which is not sufficient to call Graph API endpoints.

    For now, you can use the single tenant or multi-tenant option while registering your application in B2C tenant to support standard Azure AD functionality.

    To update user's password, delegated permission (Directory.AccessAsUser.All) need to add in API permissions. You can acquire the token using Authorization Code flow and use this token as bearer token to call Graph API.

    Client credential flow is not supported to update user's password as application permissions are not supported to change password which require user's interaction to provide the current password.

    Hope this will help.

    Thanks,
    Shweta

    ---------------------------------------

    Please remember to "Accept Answer" if answer helped you.

    0 comments No comments

  2. JS Arya 46 Reputation points
    2022-06-07T07:47:41.783+00:00

    My requirement is....

    In my application there will be multiple customers, they will have their own b2c Applications defined.

    Each application will have their own users, we are creating users using Azure AD B2C and they are getting created successfully. Now the users will login to the system and from the profile page they can change the password.

    Is there any solution which can enable the b2c user to change the password?