[SalesForce] System.SetPassword for setting Password does not work in APEX but works in Anonymous Execution

We are trying to create community users and contacts for our accounts through an apex class. In this class we use System.setPassword to set the password of the newly created users. We get no errors or exceptions when anonymously executing this class.

However, when we try to login this user using its credentials set in the program, the login fails. The login history of the user says Status = 'Invalid Password'.

Id profId = [SELECT Id FROM Profile WHERE Name = 'Community User' LIMIT 1].Id;
Account a = new Account(Name = 'testacccount');
insert a;
Contact c = new Contact(AccountId = a.Id,
                       FirstName = 'testfirst',
                       LastName = 'testlast',
                       Email = 'testaccount@test.ourwebsite.com');
insert c;
User u = new User(ContactId = c.Id,
                  Alias = 'MSstA5',
                 FirstName = c.FirstName,
                 LastName = c.LastName,
                 Email = c.Email,
                 Username = c.Email,
                 ProfileId = profId,
                 EmailEncodingKey = 'ISO-8859-1',
                 LanguageLocaleKey = 'en_US',
                 LocaleSidKey = 'en_US',
                 TimeZoneSidKey = 'America/New_York');
insert u;

string passwordstring = 'qwer1234';
                      try {
                System.setPassword(portalUser.id, passwordstring);
              }
          catch(Exception ex){
                System.debug('User Passwpord EXC:' + ex.getMessage());
                             }

And another interesting thing is that if we set the password by directly executing the same code (mentioned below) in the anonymous execution window, the password is correctly set and user is able to login.

ID userid = '0050Q0000025BvSQAU';
string passwordstring = 'qwer1234';

 try {
      System.setPassword(userid, passwordstring);
      }

 catch(Exception ex){
      System.debug('User Passwpord EXC:' + ex.getMessage());
                    }

So the ultimate problem is that I am unable to set the password for the user in the APEX class and login the user using the same password.

  1. I also waited for like 24 hours and then tried logging in but it did
    not work.
  2. I tried hard coding the password and then through a variable(like in the above code) as well.
  3. The following questions are also similar to my problem, System.SetPassword During User Creation Sets Password But User Cannot Login?, Issue creating user and setting password

Please help out in any way possible, thank you!

Best Answer

For community users, you need to use Site methods: createExternalUser(...) (or createPersonAccountPortalUser(...) if you're using Person Accounts) and login(..). System.setPassword(...) is intentionally limited since it operates at the baseline org level. Site methods have fewer restrictions because they're sandboxed by the community.