Share Your Experience With Others

How To Reset and Change User Password Using Apex

So today we will see how we can reset and changes user’s password using apex

In Salesforce, we have two methods to do it.

  • resetPassword(Id userId, Boolean sendUserEmail)
    • This method resets the password for the specified user.
    • When the user logs in with the new password, they are prompted to enter a new password, and to select a security question and answer if they haven’t already.
    • If you specify true for sendUserEmail, the user is sent an email notifying them that their password was reset.
  • setPassword(Id userId, String password)
    • When the user logs in with this password, they are not prompted to create a new password.
    • Password will be changed successfully without any notification to the user.

For example:

List<User> sfdcUsers = new List<User>();
//you can pass users list here or mention like this or can use string for single username
sfdcUsers = [SELECT Id, Name FROM User WHERE Username in ('username1','username2','username3','username4')];
 
for(User u : sfdcUsers){
    //For reset User password
    System.resetPassword(u.Id, true);
	
    //For set User password
    System.setPassword(u.Id, 'password');
}

Using this apex code we can create a visualforce page, an aura or lightning web component, then users will not need to run it manually and they can reset using UI.

Leave a comment