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.
The following are methods for UserManagement.
public static void deregisterVerificationMethod(Id userId, Auth.VerificationMethod method)
Type: void
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.
global static String formatPhoneNumber(String countryCode, String phoneNumber)
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:
Now, consider the following examples.
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.
global with sharing class PhoneRegistrationController { //Input variables global String countryCode {get; set;} global String phoneNumber {get; set;} global String addPhoneNumber() { if(countryCode == null) return 'Country code is required'; if(phoneNumber == null) return 'Phone number is required'; String userId = UserInfo.getUserId(); User u = [SELECT Id FROM User WHERE Id=:userId LIMIT 1]; String formatNum = System.UserManagement.formatPhoneNumber(countryCode, phoneNumber); u.MobilePhone = formatNum; update u; return null; } }
As long as the country code and phone number are separated, formatPhoneNumber returns a value in the proper format.
public static String initPasswordlessLogin(Id userId, Auth.VerificationMethod method)
First call the initPasswordlessLogin method to initiate an authentication challenge. This method:
Then call verifyPasswordlessLogin, which, if the user enters the verification code correctly, logs in the user.
public static String initRegisterVerificationMethod(Auth.VerificationMethod method)
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.
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.
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.
public void registerUser() { try { exceptionText=''; String userId = UserInfo.getUserId(); User u = [Select MobilePhone, Id from User Where Id=:userId]; currPhone = u.MobilePhone; mobilePhone = getFormattedSms(mobilePhone); if (mobilePhone != null && mobilePhone != '') { u.MobilePhone = mobilePhone; update u; // We're updating the email and phone number before verifying. Roll back // the change in the verify API if it is unsuccessful. exceptionText = System. UserManagement.initRegisterVerificationMethod(Auth.VerificationMethod.SMS); if(exceptionText!= null && exceptionText!=''){ isInit = false; showInitException = true; } else { isInit = false; isVerify = true; } } else { showInitException = true; } } catch (Exception e) { exceptionText = e.getMessage(); isInit = false; showInitException = true; } } public void verifyUser() { // Take the user’s input for the code sent to their phone number exceptionText = System.UserManagement. verifyRegisterVerificationMethod(code, Auth.VerificationMethod.SMS); if(exceptionText != null && exceptionText !=''){ showInitException = true; } else { //Success } }
public static String initSelfRegistration(Auth.VerificationMethod method, User user)
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.
This code contains the result of a verification challenge that registers a new user.
String id = System.UserManagement.initSelfRegistration (Auth.VerificationMethod.SMS, user); Auth.VerificationResult res = System.UserManagement.verifySelfRegistration (Auth.VerificationMethod.SMS, id, ‘123456’, null); if(res.success == true){ //redirect }
public static String initVerificationMethod(Auth.VerificationMethod method)
Use this method along with its paired verifyVerificationMethod to customize a verification service for EMAIL, SMS, or SALESFORCE_AUTHENTICATOR verification methods. The returned identifier from initVerificationMethod must be passed into verifyVerificationMethod.
First invoke the initVerificationMethod method to send a verification code to the user’s email or phone number, or to send a push notification to the Salesforce Authenticator. The user then enters the code or approves the push notification. If the verification code isn’t valid or the push notification isn’t approved, the service returns an error message.
This example shows two-factor authentication using email.
public void initVerification() { // user will receive code on their registered verified email identifier = UserManagement.initVerificationMethod(Auth.VerificationMethod.EMAIL); } public Auth.VerificationResult verifyVerification() { // requiring identifier from the initVerification // the code will need to be entered in this method return UserManagement.verifyVerificationMethod(identifier, code , Auth.VerificationMethod.EMAIL); }
public static String initVerificationMethod(Auth.VerificationMethod method, String actionName, Map<String,String> extras)
Type: String
The returned identifier must be passed into verifyVerificationMethod method.
Use this method along with its paired verifyVerificationMethod to customize a verification service for EMAIL, SMS, or SALESFORCE_AUTHENTICATOR verification methods. The returned identifier from initVerificationMethod must be passed into verifyVerificationMethod method.
First invoke the initVerificationMethod method to send a verification code to the user’s email or phone number, or to send a push notification to the Salesforce Authenticator. The user then enters the code or approves the push notification. If the verification code isn’t valid or the push notification isn’t approved, the service returns an error message.
This example shows two-factor authentication using the Salesforce Authenticator. In this example, the actionName parameter is set to the default setting and the extra parameter settings are set to false.
public void initVerification() { // user will receive push notification on their registered 2FA devices identifier = UserManagement.initVerificationMethod(Auth.VerificationMethod.SALESFORCE_AUTHENTICATOR); } public Auth.VerificationResult verifyVerification() { // requiring identifier from the initVerification // user will need to take the action on their registered 2FA devices return UserManagement.verifyVerificationMethod(identifier, '' , Auth.VerificationMethod.SALESFORCE_AUTHENTICATOR); }
This example shows two-factor authentication using the Salesforce Authenticator. In this example, the actionName parameter is set to Connect to My Salesforce Org and the challenge_required extra parameter is set to true.
public void initVerification() { Map<String,String> extras = new Map<String,String>(); extras.put('challenge_required','true'); // user will receive push notification in their registered 2FA devices identifier = UserManagement.initVerificationMethod(Auth.VerificationMethod.SALESFORCE_AUTHENTICATOR, 'Connect to My Salesforce Org', extras); } public Auth.VerificationResult verifyVerification() { // requiring identifier from the initVerification // user will need to take the action on their registered 2FA devices return UserManagement.verifyVerificationMethod(identifier, '' , Auth.VerificationMethod.SALESFORCE_AUTHENTICATOR); }
public static void obfuscateUser(Id userId, String username)
Type: void
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 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.
public static void obfuscateUser(Id userId)
Type: void
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 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.
public class UserManagementController{ public List <User> users {get; set;} public UserManagementController() { Profile p = [select id from profile where name = 'Customer Community User']; users = [select username, id from User where profileId=:p.id AND isactive=true]; } //Use method with extreme caution. Data can't be recovered. @InvocableMethod(label='User Management' description='Obfuscate User data and more') static public void obfuscate(List<User> users) { String uid = ApexPages.currentPage().getParameters().get('uid'); if(uid == null) return; User u = [select contactId from user where id=:uid]; System.UserManagement.obfuscateUser(uid); if(u.contactId != null) { List <Contact> contacts = [select id from Contact where id=:u.contactId LIMIT 1]; if (contacts == null || contacts.isEmpty() == true) return; delete contacts; } } }
public static System.PageReference registerVerificationMethod(Auth.VerificationMethod method, String startUrl)
Type:System.PageReference
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:
PageReference pr = System.UserManagement.registerVerificationMethod(Auth.VerificationMethod.TOTP,startUrl); PageReference p = System.UserManagement.deregisterVerificationMethod(userId,Auth.VerificationMethod.SALESFORCE_AUTHENTICATOR);
This method is available in API version 43.0 and later.
public static Boolean sendAsyncEmailConfirmation(String userId, String emailTemplateId, String networkId, String startUrl)
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.
System.UserManagement.sendAsyncEmailConfirmation('005RM000001a0Ox', '00XRM000000hxnG','0DBRM000000015i', '/s/contactsupport');
public static Auth.VerificationResult verifyPasswordlessLogin(Id userId, Auth.VerificationMethod method, String identifier, String code, String startUrl)
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.
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.
For an example, see Auth.VerificationResult.
public static String verifyRegisterVerificationMethod(String code, Auth.VerificationMethod method)
Type: String
If the user enters an incorrect verification code, the method returns an error message.
If the verification code is incorrect, an error message is returned.
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.
public void registerUser() { try { exceptionText=''; String userId = UserInfo.getUserId(); User u = [Select MobilePhone, Id from User Where Id=:userId]; currPhone = u.MobilePhone; mobilePhone = getFormattedSms(mobilePhone); if (mobilePhone != null && mobilePhone != '') { u.MobilePhone = mobilePhone; update u; // We're updating the email and phone number before verifying. Roll back // the change in the verify API if it is unsuccessful. exceptionText = System. UserManagement.initRegisterVerificationMethod(Auth.VerificationMethod.SMS); if(exceptionText!= null && exceptionText!=''){ isInit = false; showInitException = true; } else { isInit = false; isVerify = true; } } else { showInitException = true; } } catch (Exception e) { exceptionText = e.getMessage(); isInit = false; showInitException = true; } } public void verifyUser() { // Take the user’s input for the code sent to their phone number exceptionText = System.UserManagement. verifyRegisterVerificationMethod(code, Auth.VerificationMethod.SMS); if(exceptionText != null && exceptionText !=''){ showInitException = true; } else { //Success } }
public static Auth.VerificationResult verifySelfRegistration(Auth.VerificationMethod method, String identifier, String code, String startUrl)
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.
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.
This code contains the result of a verification challenge that registers a new user.
String id = System.UserManagement.initSelfRegistration (Auth.VerificationMethod.SMS, user); Auth.VerificationResult res = System.UserManagement.verifySelfRegistration (Auth.VerificationMethod.SMS, id, ‘123456’, null); if(res.success == true){ //redirect }
public static String verifyVerificationMethod(String identifier, String code, Auth.VerificationMethod method)
Type: VerificationResult
Use this method along with its paired initVerificationMethod to customize a verification service for EMAIL, SMS, or SALESFORCE_AUTHENTICATOR verification methods. Or use this method alone to provide a complete verification service for PASSWORD and TOTP verification methods.
This method checks whether the user entered the correct verification code or password. If the verification code or password is correct, the method verifies the user’s identity.
If the verification code or password isn’t valid, the service returns an error message.
This example shows two-factor authentication using email.
public void initVerification() { // user will receive code on their registered verified email identifier = UserManagement.initVerificationMethod(Auth.VerificationMethod.EMAIL); } public Auth.VerificationResult verifyVerification() { // requiring identifier from the initVerification // the code will need to be entered in this method return UserManagement.verifyVerificationMethod(identifier, code , Auth.VerificationMethod.EMAIL); }
The next two examples show two-factor authentication using only the verifyVerificationMethod for password and TOTP verifications.
public Auth.VerificationResult verifyVerification() { // user will enter their password as a param in the verifyVerificationMethod for password verification method return UserManagement.verifyVerificationMethod('', password , Auth.VerificationMethod.PASSWORD); }
public Auth.VerificationResult verifyVerification() { // user will enter their registered time-based one-time password (TOTP) code (token) return UserManagement.verifyVerificationMethod('', code , Auth.VerificationMethod.TOTP); }