I have a method that creates a new user and sets a custom password, everything works fine to the point where I try to log in with the new user and get an error that the login details are incorrect. Even the login history for that user does not show any entry stating that the password was incorrect, etc.
I have verified that the username and password both are correct, and it works when I do a subsequent setPassword() using the console.
Example:
User newUser = New User(); //...set user fields insert newUser; String password = getPassword(8); system.setPassword(newUser.Id, password); //...email user the password
When I run this in the console the same problem occurs:
User u = new User(); u.username = 'test@test.com'; u.email = 'test@test.com'; u.lastName = 'test'; u.firstName = 'test'; u.alias = 'test1236'; u.languagelocalekey = 'en_US'; u.localesidkey = UserInfo.getLocale(); u.emailEncodingKey = 'UTF-8'; u.timeZoneSidKey = 'America/Los_Angeles'; u.profileId = '00eG0000000FgyJ'; insert u; system.setPassword(u.id, 'testpassword1');
*UPDATE
I can login after 5 minutes or so after the user is created, I have tried on two different orgs.
Answer
The authentication mechanism seems to have a replication delay. Changing your user name results in an email being sent to you:
Dear Mr. User,
Your username has changed.
New username: ABC
Old username: XYZ
The new username may take several minutes to become fully functional.
We recommend you log in with the following link for the next 24 hours
to avoid problems.https://na1.salesforce.com/?c=…
If you can’t click the link, please copy and paste it into your
browser.Thank you, salesforce.com
I suspect that this same issue occurs when creating a new user; the user is only able to log in immediately because of the magic link they are sent in a new user email. When creating the user through other means, they will most likely experience a delay before they are able to log in using the provided user name.
Attribution
Source : Link , Question Author : rumdumdum , Answer Author : sfdcfox