Newer Version Available
UserManagement Class
Namespace
Usage
Let users register and deregister identity verification methods. Create custom Login and Verify pages for passwordless login and self-registration. Convert mobile phone numbers to the proper format before registering users. Scramble user data when users request that Salesforce remove their personal information.
This class is available in API version 43.0 and later.
UserManagement Methods
The following are methods for UserManagement.
deregisterVerificationMethod(userId, method)
Signature
public static void deregisterVerificationMethod(Id userId, Auth.VerificationMethod method)
Parameters
- userId
- Type: Id
- User ID of the user deregistering the verification method.
- method
- Type: Auth.VerificationMethod
- Verification method used to verify the identity of the user.
Return Value
Type: void
Usage
Use this method to deregister an existing identity verification method. For example, your users can deregister a phone number when their phone number changes. While only end users can register an identity verification method, you and your users can deregister one. Keep this behavior in mind when you implement a custom registration page.
This method is available in API version 43.0 and later.
formatPhoneNumber(countryCode, phoneNumber)
Signature
global static String formatPhoneNumber(String countryCode, String phoneNumber)
Parameters
Usage
Use this method to ensure a user’s mobile phone number is formatted as required by Salesforce. Then use the method’s return value to update the mobile field of the user’s record. This mobile number is used for SMS-based identity confirmation. For example, mobile phone numbers are stored along with other identity verification methods in Auth.VerificationMethod enum. This method is introduced in API version 43.0. It isn't available in earlier versions.
Here are some acceptable ways that users can enter their mobile number:
- +1, (415) 555-1234 (with plus signs, parentheses, and dashes)
- 1, 4155551234 (only numbers, no symbols)
- 1 , 415-555-1234 (extra spaces)
Now, consider the following examples.
- Correct examples:
- formatPhoneNumber('1', '4155551234');
- formatPhoneNumber('+1','(415) 555-1234');
- formatPhoneNumber('1', '415-555-1234');
- Incorrect example, because the country code and mobile number aren’t separated:
- formatPhoneNumber(null, '+1 415-555-1234');
- Example that doesn’t generate an error, but likely won’t work as intended:
- formatPhoneNumber('+1', '+1 (415) 555-1234');
Format Phone Number Code Example
Here's a code example that uses the formatPhoneNumber method. It gets the mobile number from the user and converts it to the format required by Salesforce. Then it updates the user’s record with the formatted mobile number.
1global with sharing class PhoneRegistrationController {
2 //Input variables
3 global String countryCode {get; set;}
4 global String phoneNumber {get; set;}
5
6 global String addPhoneNumber()
7 {
8 if(countryCode == null) return 'Country code is required';
9 if(phoneNumber == null) return 'Phone number is required';
10
11 String userId = UserInfo.getUserId();
12 User u = [SELECT Id FROM User WHERE Id=:userId LIMIT 1];
13 String formatNum = System.UserManagement.formatPhoneNumber(countryCode, phoneNumber);
14 u.MobilePhone = formatNum;
15 update u;
16 return null;
17 }
18
19}As long as the country code and phone number are separated, formatPhoneNumber returns a value in the proper format.
initPasswordlessLogin(userId, method)
Signature
public static String initPasswordlessLogin(Id userId, Auth.VerificationMethod method)
Parameters
- userId
- Type: Id
- ID of the user who’s logging in.
- method
- Type: Auth.VerificationMethod
- Method used to verify the user’s identity, which can be EMAIL or SMS.
Usage
First call the initPasswordlessLogin method to initiate an authentication challenge. This method:
- Gets the user ID and verification method, such as EMAIL or SMS, from the Login page.
- Looks up the user and checks that the user is unique and active.
- Sends a verification code to the user.
- Adds an entry for the verification attempt to the Identity Verification History log, assigning an identifier to the verification attempt and setting the status to User challenged, waiting for response.
- Adds an entry for the Passwordless Login to the Login History log.
- Returns the identifier to verifyPasswordlessLogin to link the transactions.
Then call verifyPasswordlessLogin, which, if the user enters the verification code correctly, logs in the user.
initRegisterVerificationMethod(method)
Signature
public static String initRegisterVerificationMethod(Auth.VerificationMethod method)
Parameters
- method
- Type: Auth.VerificationMethod
- Method used to verify the user’s identity, which can be EMAIL or SMS.
Return Value
Type: String
The method returns an error message if the phone number is already registered, the user is not external, or if the context is not a community.
Usage
Use this method along with its paired verifyRegisterVerificationMethod to customize the process for registering a user’s verification method using a Visualforce Verify page.
First call the initRegisterVerificationMethod method to get the verification code sent to the user as input, and validate it. If the verification code isn’t valid, it returns an error message.
Example
Here’s a code example that registers a user’s phone number as a verification method. When the user enters a verification code on the Visualforce page, it invokes registerUser(). The method gets the User ID of the user who’s registering the verification method and the user’s phone number. It also gets the user’s registration status to check whether the phone number is verified already. If the user is registered with a different phone number, the number is updated.
1public void registerUser() {
2 try {
3 exceptionText='';
4 String userId = UserInfo.getUserId();
5 User u = [Select MobilePhone, Id from User Where Id=:userId];
6 currPhone = u.MobilePhone;
7 mobilePhone = getFormattedSms(mobilePhone);
8 if (mobilePhone != null && mobilePhone != '') {
9 u.MobilePhone = mobilePhone;
10 update u;
11 // We're updating the email and phone number before verifying. Roll back
12 // the change in the verify API if it is unsuccessful.
13 exceptionText = System.
14 UserManagement.initRegisterVerificationMethod(Auth.VerificationMethod.SMS);
15 if(exceptionText!= null && exceptionText!=''){
16 isInit = false;
17 showInitException = true;
18 } else {
19 isInit = false;
20 isVerify = true;
21 }
22 } else {
23 showInitException = true;
24 }
25 } catch (Exception e) {
26 exceptionText = e.getMessage();
27 isInit = false;
28 showInitException = true;
29 }
30 }
31
32public void verifyUser() {
33 // Take the user’s input for the code sent to their phone number
34 exceptionText = System.UserManagement.
verifyRegisterVerificationMethod(code, Auth.VerificationMethod.SMS);
35 if(exceptionText != null && exceptionText !=''){
36 showInitException = true;
37 } else {
38 //Success
39 }
40}initSelfRegistration(method, user)
Signature
public static String initSelfRegistration(Auth.VerificationMethod method, User user)
Parameters
- method
- Type: Auth.VerificationMethod
- Method used to verify the identity of the user, which can be EMAIL or SMS.
- user
- Type: User
- User object to insert after successful registration.
Usage
By default, when users sign up for your community with an email address or phone number, Salesforce sends them a verification code. At the same time, it generates a Verify page for users to confirm their identity. You can replace the default Salesforce Verify page with your own Visualforce page and then invoke the verification process.
Call this method to initiate the authentication challenge, and include a User object to insert if the registration is successful. The method returns the identifier for the self-registration attempt.
Then call verifySelfRegistration, which, if the user enters the verification code correctly, logs in the user.
Example
This code contains the result of a verification challenge that registers a new user.
1String id = System.UserManagement.initSelfRegistration
2 (Auth.VerificationMethod.SMS, user);
3 Auth.VerificationResult res = System.UserManagement.verifySelfRegistration
4 (Auth.VerificationMethod.SMS, id, ‘123456’, null);
5 if(res.status == SUCCESS){
6 //redirect
7}obfuscateUser(userId, username)
Signature
public static void obfuscateUser(Id userId, String username)
Parameters
Return Value
Type: void
Usage
This method is introduced in API version 43.0. It isn't available in earlier versions.
You can use the obfuscateUser method to protect the personal information of your org’s users. When invoked, Salesforce permanently scrambles the user’s object data and replaces it with random character strings. The user’s detail page exists, but the fields contain meaningless strings of characters. Salesforce merely obfuscates (scrambles) personal data because you can't delete a user in Salesforce; you can only disable or deactivate a user. In other words, the user record remains in the database and this method performs a soft delete.
Considerations
- This method requires that the org’s User Management setting, Scramble Specific Users' Data, is enabled from Setup.
- This method affects the standard fields of the user object—excluding a few fields such as the user ID, timezone, locale, and profile.
- It is recommended that you note the user's ID and other attributes for post processing, such as the email address, if you want to send the user a confirmation.
- This method changes only the user object. The association between the user and other objects is removed, but no other objects are changed. For example, contact, ThirdPartyAccountLink (TPAL), and user password authentication (UPA) objects remain unchanged.
This method is part of our effort to protect users’ personal data and privacy. For more information on what you can do to actively protect user data, see Data Protection and Privacy in Salesforce Help.
obfuscateUser(userId)
Signature
public static void obfuscateUser(Id userId)
Parameters
- userId
- Type: Id
- ID of the user whose data this method scrambles.
Return Value
Type: void
Usage
This method is introduced in API version 43.0. It isn't available in earlier versions.
You can use the obfuscateUser method to protect the personal information of your org’s users. When invoked, Salesforce permanently scrambles the user’s object data and replaces it with random character strings. The user’s detail page exists, but the fields contain meaningless strings of characters. Salesforce merely obfuscates (scrambles) personal data because you can't delete a user in Salesforce; you can only disable or deactivate a user. In other words, the user record remains in the database and this method performs a soft delete.
Considerations
- This method requires that the org’s User Management setting, Scramble Specific Users' Data, is enabled from Setup.
- This method affects the standard fields of the user object—excluding a few fields such as the user ID, timezone, locale, and profile.
- It is recommended that you note the user's ID and other attributes for post processing, such as the email address, if you want to send the user a confirmation.
- This method changes only the user object. The association between the user and other objects is removed, but no other objects are changed. For example, contact, ThirdPartyAccountLink (TPAL), and user password authentication (UPA) objects remain unchanged.
This method is part of our effort to protect users’ personal data and privacy. For more information on what you can do to actively protect user data, see Data Protection and Privacy in Salesforce Help.
ObfuscateUser Code Example
1public class UserManagementController{
2 public List <User> users {get; set;}
3
4 public UserManagementController()
5 {
6 Profile p = [select id from profile where name = 'Customer Community User'];
7
8 users = [select username, id from User where profileId=:p.id AND isactive=true];
9 }
10
11 //Use method with extreme caution. Data can't be recovered.
12 @InvocableMethod(label='User Management' description='Obfuscate User data and more')
13 static public void obfuscate(List<User> users)
14 {
15 String uid = ApexPages.currentPage().getParameters().get('uid');
16
17 if(uid == null)
18 return;
19
20 User u = [select contactId from user where id=:uid];
21
22 System.UserManagement.obfuscateUser(uid);
23
24 if(u.contactId != null)
25 {
26 List <Contact> contacts = [select id from Contact where id=:u.contactId LIMIT 1];
27 if (contacts == null || contacts.isEmpty() == true)
28 return;
29
30 delete contacts;
31 }
32 }
33}registerVerificationMethod(method, startUrl)
Signature
public static System.PageReference registerVerificationMethod(Auth.VerificationMethod method, String startUrl)
Parameters
- method
- Type: Auth.VerificationMethod
- Verification method used to verify the identity of the user.
- startUrl
- Type: String
- Path to the page that users see after they log in.
Return Value
Type:System.PageReference
Usage
Use this method to enable users to complete identity verification, such as 2FA, or to log in to their community without a password. Users register these methods to verify their identity when logging in. You create a custom registration page when implementing mobile-centric passwordless logins. See VerifyPasswordlessLogin.
The PageReference returned by registerVerificationMethod redirects the user to the Salesforce Verify page. If the user enters the correct code, the user is redirected to the community page specified by the start URL. For example:
1PageReference pr = System.UserManagement.registerVerificationMethod(Auth.VerificationMethod.TOTP,startUrl);
2PageReference p = System.UserManagement.deregisterVerificationMethod(userId,Auth.VerificationMethod.SALESFORCE_AUTHENTICATOR);This method is available in API version 43.0 and later.
sendAsyncEmailConfirmation(userId, emailTemplateId, networkId, startUrl)
Signature
public static Boolean sendAsyncEmailConfirmation(String userId, String emailTemplateId, String networkId, String startUrl)
Parameters
- userId
- Type: String
- ID of the user to receive the email confirmation.
- emailTemplateId
- Type: String
- ID of the email template in which the verification link is defined.
- networkId
- Type: String
- ID of the community.
- startUrl
- Type: String
- The user is redirected to this page after verification, with a success or error message as the parameter. If null, the user is redirected to the login page.
Usage
Sending an async email message is good practice to ensure that users are registered with a valid email address that they truly own. To determine which users receive an email with the verification link, check whether the User Verified Email field in the User detail page is set to true. You can also get this information from the TwoFactorMethodsInfo API.
Send async email verification to external users to verify their email address. External users must verify their email address before they can log in with email OTP (passwordless login).
The error code and description are passed as query parameters so that you can process any errors when building a custom landing page.
Example
1System.UserManagement.sendAsyncEmailConfirmation('005RM000001a0Ox',
2'00XRM000000hxnG','0DBRM000000015i', '/s/contactsupport');verifyPasswordlessLogin(userId, method, identifier, code, startUrl)
Signature
public static Auth.VerificationResult verifyPasswordlessLogin(Id userId, Auth.VerificationMethod method, String identifier, String code, String startUrl)
Parameters
- userId
- Type: Id
- ID of the user who’s logging in.
- method
- Type: Auth.VerificationMethod
- Method used to verify the identity of the user, which can be either EMAIL or SMS.
- identifier
- Type: String
- ID of the verification attempt received from the initPasswordlessLogin method.
- code
- Type: String
- Code used to verify the identity of the user.
- startUrl
- Type: String
- The page where the user is directed after successful login.
Return Value
Type: Auth.VerificationResult
Result of the verification challenge, which includes the message displayed, and where the user is directed if they enter the verification code correctly.
Usage
Call this method to complete the passwordless login authentication process. It validates the verification method and verification code. It also checks that the identifier is the same as the one returned by initPasswordlessLogin.
Example
For an example, see Auth.VerificationResult.
verifyRegisterVerificationMethod(code, method)
Signature
public static String verifyRegisterVerificationMethod(String code, Auth.VerificationMethod method)
Parameters
- code
- Type: String
- Code used to verify the identity of the user.
- method
- Type: Auth.VerificationMethod
- Method used to verify the identity of the user, which can be either EMAIL or SMS.
Return Value
Type: String
If the user enters an incorrect verification code, the method returns an error message.
Usage
- Confirms that the user entered the correct verification code
- From the user’s detail page, updates the user's verification method status (sets the verification bit)
- Sends an email to the user confirming that a verification method has been added to their record
If the verification code is incorrect, an error message is returned.
Example
Here’s a code example that registers a user’s phone number as a verification method. When the user enters a verification code on the Visualforce page, it invokes registerUser(). The method gets the User ID of the user who’s registering the verification method and the user’s phone number. It also gets the user’s registration status to check whether the phone number is verified already. If the user is registered with a different phone number, the number is updated.
1public void registerUser() {
2 try {
3 exceptionText='';
4 String userId = UserInfo.getUserId();
5 User u = [Select MobilePhone, Id from User Where Id=:userId];
6 currPhone = u.MobilePhone;
7 mobilePhone = getFormattedSms(mobilePhone);
8 if (mobilePhone != null && mobilePhone != '') {
9 u.MobilePhone = mobilePhone;
10 update u;
11 // We're updating the email and phone number before verifying. Roll back
12 // the change in the verify API if it is unsuccessful.
13 exceptionText = System.
14 UserManagement.initRegisterVerificationMethod(Auth.VerificationMethod.SMS);
15 if(exceptionText!= null && exceptionText!=''){
16 isInit = false;
17 showInitException = true;
18 } else {
19 isInit = false;
20 isVerify = true;
21 }
22 } else {
23 showInitException = true;
24 }
25 } catch (Exception e) {
26 exceptionText = e.getMessage();
27 isInit = false;
28 showInitException = true;
29 }
30 }
31
32public void verifyUser() {
33 // Take the user’s input for the code sent to their phone number
34 exceptionText = System.UserManagement.
verifyRegisterVerificationMethod(code, Auth.VerificationMethod.SMS);
35 if(exceptionText != null && exceptionText !=''){
36 showInitException = true;
37 } else {
38 //Success
39 }
40}verifySelfRegistration(method, identifier, code, startUrl)
Signature
public static Auth.VerificationResult verifySelfRegistration(Auth.VerificationMethod method, String identifier, String code, String startUrl)
Parameters
- method
- Type: Auth.VerificationMethod
- Method used to verify the identity of the user, which can be either EMAIL or SMS.
- identifier
- Type: String
- The unique identifier received from the initSelfRegistration method.
- code
- Type: String
- Code used to verify the identity of the user.
- startUrl
- Type: String
- The page where the user is directed after successful self-registration.
Return Value
Type: Auth.VerificationResult
Result of the verification challenge, which includes the message displayed, and where the user is directed when they enter the verification code correctly.
Usage
By default, when users sign up for your community with an email address or phone number, Salesforce sends them a verification code and generates a Verify page. This Verify page is where users enter the verification code to confirm their identity. You can replace this Salesforce-generated Verify page with a custom Verify page that you create with Visualforce. Then you invoke the verification process with Apex methods.
First, call the initSelfRegistration method, which returns the identifier of the user to create. Then call this verifySelfRegistration method to complete the verification process. If the user enters the verification code correctly, the user is created and directed to the page specified in the startURL.
This method returns the verification result, which contains the verification status and, if the user is created, the session ID. If the verification method is SMS, the User object must contain a properly formatted mobile number, which is country code, space, and then phone number, for example, +1 1234567890. Use System.UserManagement.formatPhoneNumber to ensure that the phone number is formatted correctly.
Example
This code contains the result of a verification challenge that registers a new user.
1String id = System.UserManagement.initSelfRegistration
2 (Auth.VerificationMethod.SMS, user);
3 Auth.VerificationResult res = System.UserManagement.verifySelfRegistration
4 (Auth.VerificationMethod.SMS, id, ‘123456’, null);
5 if(res.status == SUCCESS){
6 //redirect
7}