How to set passwords for newly created Salesforce users via Apex and implications for login behavior.
Overview
When creating new User records in Salesforce via Apex, you can call System.setPassword(userId, password) to assign an initial password. By default Salesforce prompts users to change their password on first login, but users can click “Cancel” on that prompt and still access the org. This behavior is useful for automated test-user provisioning or bulk user creation where a shared default password is convenient.
Quick Apex example
// Create a user (simplified example)
User u = new User(
Username = '[email protected]',
LastName = 'User',
Email = '[email protected]',
Alias = 'tuser',
TimeZoneSidKey = 'America/Los_Angeles',
LocaleSidKey = 'en_US',
EmailEncodingKey = 'UTF-8',
LanguageLocaleKey = 'en_US',
ProfileId = [SELECT Id FROM Profile WHERE Name='Standard User' LIMIT 1].Id
);
insert u;
// Set an initial password for the created user
System.setPassword(u.Id, 'MyInitialP@ssw0rd!');
When to use this
- Provisioning bulk test users in sandboxes or scratch orgs
- Automated integration / QA environments where consistent credentials reduce test setup time
- Internal demo orgs where administrators want temporary shared passwords
Security considerations and best practices
- Do NOT use this approach for production user onboarding unless you fully understand the security implications and have appropriate policies in place.
- Prefer sending password reset emails (UserManagement flows) for real users so they create a secure, unique password.
- If you use System.setPassword for test accounts: rotate or deactivate accounts after tests complete.
- Be aware that users can skip the change-password-on-first-login flow by cancelling, which may be acceptable for test users but not for real users.
References
Original discussion and reference: Salesforce StackExchange: Create a user without asking them to set their password
Why this matters: For Salesforce admins and developers, automating user provisioning can significantly speed test and CI workflows — but must be balanced with security controls and user lifecycle management.








Leave a Reply