Salesforce Apex how to reset any user password using username
•49 min read
Apex examples and important security notes. Important: System.setPassword(userId, newPassword)is the standard Apex API to set a user’s password. It must be run by a context that has permission to manage users (typically an admin) and will fail for SSO/federated users or if password policy prevents the password.
Simple utility class (callable from Execute Anonymous or an admin-run context)
public without sharing class PasswordResetUtil {
/**
* Reset password for a user identified by username.
* - Throws a descriptive exception if user not found, inactive, SSO user, or password invalid.
*/
public static void resetPasswordByUsername(String username, String newPassword, Boolean notifyUser) {
if (String.isBlank(username)) {
throw new IllegalArgumentException('username is required');
}
// Find user
User u;
try {
u = [SELECT Id, IsActive, FederationIdentifier, Email, Name
FROM User WHERE Username = :username LIMIT 1];
} catch (Exception ex) {
// no rows or other query error
throw new IllegalArgumentException('User not found for username: ' + username);
}
if (!u.IsActive) {
throw new IllegalStateException('Cannot reset password: user is inactive.');
}
// Many SSO/federated users should not have their Salesforce password changed
if (u.FederationIdentifier != null && u.FederationIdentifier != '') {
throw new IllegalStateException('Cannot reset password for federated/SSO user.');
}
// Set the password (will enforce org password policies)
try {
System.setPassword(u.Id, newPassword);
} catch (Exception ex) {
// usually password policy violation or insufficient privileges
throw new IllegalStateException('Failed to set password: ' + ex.getMessage());
}
// Optional: notify user by email
if (notifyUser) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(new String[] { u.Email });
mail.setSubject('Your Salesforce password has been reset');
mail.setPlainTextBody('Hello ' + u.Name + ',\n\n'
+ 'Your Salesforce password for username ' + username + ' was reset by an administrator.'
+ '\nIf this was unexpected, contact your administrator immediately.'
+ '\n\n(Do not reply to this automated message.)');
try {
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
} catch (Exception e) {
// don't fail the operation just because email couldn't be sent
System.debug('Email send failed: ' + e.getMessage());
}
}
}
}
JavaScriptUsage in Execute Anonymous (as an admin):
PasswordResetUtil.resetPasswordByUsername('jane.doe@example.com', 'NewP@ssw0rd123!', true);
JavaScriptGenerate a random compliant password (example)
This helper generates a mixed-character password. Note: it tries to produce complexity but you should confirm it meets your org's password policy.
public class PasswordHelper {
public static String generateRandomPassword(Integer length) {
if (length == null || length < 8) length = 12; // default
String upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
String lower = 'abcdefghijklmnopqrstuvwxyz';
String digits = '0123456789';
String special = '!@#$%&*()-_=+[]{};:,.<>?';
String all = upper + lower + digits + special;
StringBuilder sb = new StringBuilder();
// ensure at least one of each
sb.append(upper.substring(Math.mod(Math.abs(Crypto.getRandomInteger()), upper.length()), 1));
sb.append(lower.substring(Math.mod(Math.abs(Crypto.getRandomInteger()), lower.length()), 1));
sb.append(digits.substring(Math.mod(Math.abs(Crypto.getRandomInteger()), digits.length()), 1));
sb.append(special.substring(Math.mod(Math.abs(Crypto.getRandomInteger()), special.length()), 1));
while (sb.length() < length) {
Integer idx = Math.mod(Math.abs(Crypto.getRandomInteger()), all.length());
sb.append(all.substring(idx, idx+1));
}
// shuffle
List<String> chars = new List<String>();
for (Integer i=0;i<sb.length();i++) chars.add(sb.substring(i,i+1));
Collections.shuffle(chars);
return String.join(chars,'');
}
}
JavaScriptExample:
String pwd = PasswordHelper.generateRandomPassword(14);
PasswordResetUtil.resetPasswordByUsername('user@example.com', pwd, true);
JavaScriptREST endpoint example (SECURE THIS — only for admin use)
If you expose a REST endpoint, require admin-only access (e.g., check profile or a custom permission) before performing the reset:
@RestResource(urlMapping='/admin/resetpw/*')
global with sharing class AdminPasswordResetRest {
@HttpPost
global static String doReset() {
// Example: ensure current user is admin — adjust to your org's security model
// Replace with check of Profile, PermissionSet, or Custom Permission
if (!isCurrentUserAdmin()) {
throw new RestResourceException('Unauthorized');
}
RestRequest req = RestContext.request;
Map<String, Object> body = (Map<String, Object>) JSON.deserializeUntyped(req.requestBody.toString());
String username = (String) body.get('username');
String password = (String) body.get('password');
Boolean notify = body.containsKey('notify') ? (Boolean) body.get('notify') : false;
PasswordResetUtil.resetPasswordByUsername(username, password, notify);
return 'OK';
}
private static Boolean isCurrentUserAdmin() {
// Example implementation — replace with robust permission check
Profile p = [SELECT Id, Name FROM Profile WHERE Id = :UserInfo.getProfileId()];
return p.Name.toLowerCase().contains('system administrator');
}
}
JavaScriptDo not deploy an endpoint like this without strict auth & logging.
Security & operational notes (must-read)
System.setPassword(userId, password)requires that the running user (Apex context) has appropriate privileges — typically an administrator. If not, it will throw a permissions exception.- Org password policies are enforced; attempting to set a password that violates policy will throw an exception.
- You generally cannot set passwords for federated/SSO users. Check
User.FederationIdentifier(or your SSO fields) and avoid trying to change SSO users. - Log and audit every password reset operation — it’s a privileged action.
- If exposing programmatic reset (REST, UI, Flow), restrict it to admin profiles or require a custom permission, and implement detailed logging/alerting.
- Consider using Salesforce’s built-in “Reset Password” button and the standard flows for interactive admin resets unless you absolutely need automation.
- For multi-user mass resets, implement governor limits awareness (DML limits, email limits), and run as batchable if needed.
Related Posts

How to Automatically create a follow-up Task when a Lead is converted

How You need to update a related child record whenever a parent record’s status changes, but only if the status is “Closed Won.” How would you design this in Apex?
