RegistrationHandler Interface
Namespace
Usage
RegistrationHandler Methods
The following are methods for RegistrationHandler.
createUser(portalId, userData)
Signature
public User createUser(ID portalId, Auth.UserData userData)
Parameters
- portalId
- Type: ID
- userData
- Type: Auth.UserData
Return Value
Type: User
updateUser(userId, portalId, userData)
Signature
public Void updateUser(ID userId, ID portalId, Auth.UserData userData)
Parameters
- userId
- Type: ID
- portalId
- Type: ID
- userData
- Type: Auth.UserData
Return Value
Type: Void
Storing User Information and Getting Access Tokens
The Auth.UserData class is used to store user information for Auth.RegistrationHandler. The third-party identity provider can send back a large collection of data about the user, including their username, email address, locale, and more. The Salesforce authentication provider framework converts this data into a common format with the Auth.UserData class and then sendsit to the registration handler.
If the registration handler wants to use the rest of the data, the Auth.UserData class has an attributeMap variable. The attribute map is a map of strings (Map<String, String>) for the raw values of all the data from the third party. Because the map is <String, String>, values that the third party returns that aren't strings (like an array of URLs or a map) are converted into an appropriate string representation. The map includes everything returned by the third-party authentication provider, including the items automatically converted into the common format.
To learn about Auth.UserData properties, see Auth.UserData Class.
For all authentication providers except Janrain, after a user is authenticated using a provider, the access token associated with that provider for this user can be obtained in Apex using the Auth.AuthToken Apex class. Auth.AuthToken provides two methods to retrieve access tokens. One is getAccessToken, which obtains a single access token. Use this method if the user ID is mapped to a single third-party user. If the user ID is mapped to multiple third-party users, use getAccessTokenMap, which returns a map of access tokens for each third-party user. For more information about authentication providers, see Authentication Providers in Salesforce Help.
When using Janrain as an authentication provider, you must use the Janrain accessCredentials dictionary values to retrieve the access token or its equivalent. Only some providers supported by Janrain provide an access token, while other providers use other fields. The Janrain accessCredentials fields are returned in the attributeMap variable of the Auth.UserData class. See the Janrain auth_info documentation for more information on accessCredentials.
To learn about the Auth.AuthToken methods, see Auth.AuthToken Class.
User Information in the ID Token and User Info Response
Some identity providers send additional user information in an ID token or in a user info response. To extract user information from these responses, there are some extra steps.
An ID token is formatted as a JWT and includes information about the authenticated user. If the identity provider sends an ID token, Salesforce stores the full encoded JWT in the idToken property. Salesforce also stores the decoded JWT payload of the ID token in the idTokenJSONString property.
Salesforce doesn't validate the ID token. To validate it, use methods in the Auth.JWTUtil class and pass in the encoded JWT stored in the idToken property. The methods in the Auth.JWTUtil class all return an instance of the Auth.JWT object.
Once you validate the JWT, you can use methods in the Auth.JWT class to access specific claims. For example, the Apex code in this snippet validates the ID token using a public keys endpoint from the identity provider and then retrieves the value of an email claim stored in the token.
1Auth.JWT jwt = Auth.JWTUtil.validateJWTWithKeysEndpoint(userdata.idToken, keysEndpoint, true);
2
3// Retrieve email claim from id token
4String email = (String) jwt.getAdditionalClaims().get('email');
5System.debug(email);
6Alternatively, to access specific claims in the idTokenJSONString property, you can deserialize the JSON string and then write code to retrieve the claim you want. To deserialize the idTokenJSONString, use the JSON.deserialize (jsonString, apexType) method in the System.JSON class.
The user info response, if returned by the identity provider, is also a JSON object that has been serialized into a string. The user info response is stored in the userInfoJSONString property. You can use the JSON.deserialize (jsonString, apexType) method to deserialize the user info response so that you can retrieve specific information.
This example snippet creates a custom class to store the user info response. It then deserializes the user info response in the userInfoJSONString into this custom class structure.
1public class UserInfoResponse {
2 public String preferred_username;
3 public String email;
4 public Boolean email_verified;
5 public String given_name;
6 public String family_name;
7 public String locale;
8}
9
10UserInfoResponse userInfo = (UserInfoResponse)System.JSON.deserialize(userData.userInfoJSONString, UserInfoResponse.class);
11System.debug(userInfo.email);
12Auth.RegistrationHandler Example Implementation
This example implements the Auth.RegistrationHandler interface that creates as well as updates a standard user based on data provided by the authentication provider. Error checking has been omitted to keep the example simple.
1global class StandardUserRegistrationHandler implements Auth.RegistrationHandler{
2 global User createUser(Id portalId, Auth.UserData data) {
3 User u = new User();
4 Profile p = [SELECT Id FROM profile WHERE name='Standard User'];
5 u.Username = data.username + '@salesforce.com';
6 u.Email = data.email;
7 u.LastName = data.lastName;
8 u.FirstName = data.firstName;
9 String alias = data.username;
10 if(alias.length() > 8) {
11 alias = alias.substring(0, 8);
12 }
13 u.Alias = alias;
14 u.LanguageLocaleKey = data.attributeMap.get('language');
15 u.LocaleSidKey = data.locale;
16 u.EmailEncodingKey = 'UTF-8';
17 u.TimeZoneSidKey = 'America/Los_Angeles';
18 u.ProfileId = p.Id;
19 return u;
20 }
21
22 global void updateUser(Id userId, Id portalId, Auth.UserData data) {
23 User u = new User(id=userId);
24 u.Username = data.username + '@salesforce.com';
25 u.Email = data.email;
26 u.LastName = data.lastName;
27 u.FirstName = data.firstName;
28 String alias = data.username;
29 if(alias.length() > 8) {
30 alias = alias.substring(0, 8);
31 }
32 u.Alias = alias;
33 u.LanguageLocaleKey = data.attributeMap.get('language');
34 u.LocaleSidKey = data.locale;
35 update(u);
36 }
37}The following example tests the above code.
1@isTest
2private class StandardUserRegistrationHandlerTest {
3static testMethod void testCreateAndUpdateUser() {
4 StandardUserRegistrationHandler handler = new StandardUserRegistrationHandler();
5 Auth.UserData sampleData = new Auth.UserData('testId', 'testFirst', 'testLast',
6 'testFirst testLast', 'testuser@example.org', null, 'testuserlong', 'en_US', 'facebook',
7 null, new Map<String, String>{'language' => 'en_US'});
8 User u = handler.createUser(null, sampleData);
9 System.assertEquals('testuserlong@salesforce.com', u.username);
10 System.assertEquals('testuser@example.org', u.email);
11 System.assertEquals('testLast', u.lastName);
12 System.assertEquals('testFirst', u.firstName);
13 System.assertEquals('testuser', u.alias);
14 insert(u);
15 String uid = u.id;
16
17 sampleData = new Auth.UserData('testNewId', 'testNewFirst', 'testNewLast',
18 'testNewFirst testNewLast', 'testnewuser@example.org', null, 'testnewuserlong', 'en_US', 'facebook',
19 null, new Map<String, String>{'language' => 'en_US'});
20 handler.updateUser(uid, null, sampleData);
21
22 User updatedUser = [SELECT username, email, firstName, lastName, alias FROM user WHERE id=:uid];
23 System.assertEquals('testnewuserlong@salesforce.com', updatedUser.username);
24 System.assertEquals('testnewuser@example.org', updatedUser.email);
25 System.assertEquals('testNewLast', updatedUser.lastName);
26 System.assertEquals('testNewFirst', updatedUser.firstName);
27 System.assertEquals('testnewu', updatedUser.alias);
28}
29}Auth.RegistrationHandler Error Example
To limit this example to the custom exception, some code was omitted.
1global class RegHandler implements Auth.RegistrationHandler {
2
3 class RegHandlerException extends Exception {}
4
5 global User createUser(Id portalId, Auth.UserData data){
6 List<Profile> profiles = [SELECT Id, Name, UserType FROM Profile WHERE Name = 'Power User'];
7 Profile profile = profiles.isEmpty() ? null : profiles[0];
8 if(profile==null)
9 throw new RegHandlerException('Cannot find the profile. For help, contact your administrator.');
10...
11 }
12
13 global void updateUser(Id userId, Id portalId, Auth.UserData data){
14 User u = new User(id=userId);
15 u.lastName = data.lastName;
16 u.firstName = data.firstName;
17 update(u);
18 }
19}