A Salesforce Developer team was developing a Salesforce application that required the ability to reset and change user passwords programmatically.
To do this, I created an Apex class. Here, I will explain how to reset and change user password using Salesforce Apex.
Reset Current User Password Using Salesforce Apex
In the following Apex program, I explain how we can reset the currently logged-in user’s password using Salesforce Apex.
Here, I created an Apex class using the resetCurrentUserPass() method. In that method, we retrieve the current user ID using the UserInfo class and the GetUserId() method.
- SOQL: To get the current user’s details, we query for the user and pass the fetched ID in the query.
- Try block: In the try block, I execute the logic; here, we want to reset the user’s password. To reset the password, we have the system.resetPassword(UserID, SendEmailToUser) method, and in that method, we need to pass the user ID and a boolean value. If the boolean value is set to
true, Salesforce will send an email to the user with the password reset link. - Catch block: The catch block will execute if there is an issue resetting the user’s password, displaying the message we entered.
Then, execute this apex code in the anonymous window.
public class RstCurrentUserPass {
public void resetCurrentUserPass(){
Id userID = UserInfo.GetuserId();
User currentUser = [Select Id, Name From User WHERE Id =: userID];
try{
system.resetPassword(currentUser.id,true);
system.debug('The password for ' +currentUser.Name + ' has been successfully
reset');
}
catch(Exception e){
e.setmessage('There is a problem to change the user password');
}
}
}

After the code is executed, you will see the message that we entered in the try block. It will display only when the password is successfully reset.
Then, you will get an email from Salesforce support with the reset link. Clicking the link will give you a reset button, allowing you to change your password.

In this way, you can reset the user’s password for the currently logged-in user using Salesforce Apex.
Reset and Change User Password Using Salesforce Apex
You can also change the user password when you reset it. When you change the password immediately after resetting the program, you do not need to reset it manually.
In the following program, I will explain how to change a currently logged-in user’s password using Apex in Salesforce.
To change the user password, you also need to obtain the user ID. Then, using a SOQL query, get the user details and execute logic in the try block. Here, we are changing the user password for the currently logged-in user.
For that, we have the system.setPassword(User id, ‘String password’) method in the Salesforce Apex. In that method, we nee