この文章は Salesforce 機械翻訳システムを使用して翻訳されました。詳細はこちらをご参照ください。
英語に切り替える

Newer Version Available

This content describes an older version of this product. View Latest

MyDomainLoginDiscoveryHandler インターフェース

インタビューベース (2 ステップ) のログインプロセスである、[私のドメイン] のログイン検出ページを実装するために使用するハン��ラ。まず、メールアドレスや電話番号などの一意の識別子をユーザに要求します。次に、このハンドラがユーザの認証方法を決定 (検出) します。ユーザはパスワードを入力するか、ID プロバイダのログインページにリダイレクトされます。

名前空間

Auth

使用方法

MyDomainLoginDiscoveryHandler を実装すると、[私のドメイン] ユーザがユーザとパスワード以外の方法でログインできます。このハンドラには、ログインページに入力された ID 値に基づいてユーザを検索するロジックが含まれています。ID ページが送信され、送信された ID に対応するユーザが見つかると、Auth.MyDomainLoginDiscoveryHandler.login メソッドが呼び出されます。Auth.SessionManagement.finishLoginDiscovery メソッドは、ユーザを認証メカニズムに送信してから、ユーザをログインさせます。

このハンドラは、[私のドメイン] の [設定] ページで登録します。[認証設定] で、[ログインページ種別] に [検出] を選択します。[ログイン検出ハンドラ] で、Apex クラスのリストからこのハンドラを選択します。

例については、「MyDomainLoginDiscoveryHandler の実装例」を参照してください。詳細は、Salesforce ヘルプで「私のドメイン ログイン検出」を検索してください。

MyDomainLoginDiscoveryHandler メソッド

MyDomainLoginDiscoveryHandler には次のメソッドがあります。

login(identifier, startUrl, requestAttributes)

メールや電話番号などの識別子が指定された Salesforcec ユーザのログインを行います。成功した場合、開始 URL で指定されたページにユーザをリダイレクトします。

署名

public System.PageReference login(String identifier, String startUrl, Map<String,String> requestAttributes)

パラメータ

identifier
型: String
ログイン画面で Salesforce ユーザが入力した識別子 (メールアドレスや電話番号など)。
startUrl
型: String
ユーザが [私のドメイン] サブドメインに正常にログインすると表示されるページ。
requestAttributes
型: Map<String, String>
ログインページにアクセスしたときのユーザのブラウザ状態に基づくログイン要求に関する情報。requestAttributes は MyDomainUrl、IpAddress、UserAgent、Platform、Application、City、Country、Subdivision の値を渡します。City、Country、Subdivision の値は IP アドレス地理位置情報から取得されます。

戻り値

型: System.PageReference

ユーザが認証を完了するためにリダイレクトされるページの URL。

次に requestAttributes のサンプル応答を示します。

1CommunityUrl=http://my-dev-ed.my.salesforce.com:5555/discover
2IpAddress=55.255.0.0
3UserAgent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.1 Safari/605.1.15
4Platform=Mac OSX
5Application=Browser
6City=San Mateo
7Country=United States
8Subdivision=California

MyDomainLoginDiscoveryHandler の実装例

Auth.MyDomainLoginDiscoveryHandler インターフェースの例を次に示します。このサンプルクラスには、パスワード認証を使用する [私のドメイン] ログイン検出のデフォルトのロジ���クが含まれています。ニーズに合わせてコードをカスタマイズできます。requestAttributes パラメータは、検出ロジックで使用できる追加情報が含まれます。属性には、MyDomainUrl、IpAddress、UserAgent、場所情報 (国や市区群など) があります。ログインページに表示するカスタムエラーを発生させるには Auth.DiscoveryCustomErrorException を使用します。

このインターフェースを実装するには、[私のドメイン] のログインページ種別を [検出] に設定する必要があります。

1// This sample class contains the default logic for My Domain login discovery by password. 
2// You can customize the code to ensure it meets your needs. The requestAttributes parameter 
3// provides additional information you can use in the discovery logic. Attributes include MyDomainUrl, 
4// IpAddress, UserAgent, and location information (such as Country and City). 
5// Use Auth.DiscoveryCustomErrorException to throw custom errors which will be shown on login page. 
6 
7global class MyDomainDiscLoginDefaultHandler implements Auth.MyDomainLoginDiscoveryHandler {
8 
9  global PageReference login(String identifierString startUrlMap<StringString> requestAttributes) {
10   if (identifier != null) {
11        // Search for user by email 
12        List<User> users = [SELECT Id FROM User WHERE Email = :identifier AND IsActive = TRUE];
13        if (!users.isEmpty() && users.size() == 1) {
14            return discoveryResult(users[0]startUrlrequestAttributes);
15        } else {
16            throw new Auth.LoginDiscoveryException('No unique user found. User count=' + users.size());
17        }
18    }
19    throw new Auth.LoginDiscoveryException('Invalid Identifier');
20  }
21  
22  private PageReference getSsoRedirect(User userString startUrlMap<StringString> requestAttributes) {
23    // You can look up if the user should log in with SAML or an Auth Provider and return the URL to initialize SSO. For example : 
24    // SamlSsoConfig SSO = [select Id from SamlSsoConfig where DeveloperName='SamlTest' limit 1];
25    // String ssoUrl = Auth.AuthConfiguration.getSamlSsoUrl(requestAttributes.get('MyDomainUrl'), startUrl, SSO.Id);
26    // return new PageReference(ssoUrl);
27    return null;
28  }
29 
30  private PageReference discoveryResult(User userString startUrlMap<StringString> requestAttributes) {
31     PageReference ssoRedirect = getSsoRedirect(userstartUrlrequestAttributes);
32      if (ssoRedirect != null) {
33        return ssoRedirect;
34      } else {
35        return Auth.SessionManagement.finishLoginDiscovery(Auth.LoginDiscoveryMethod.passworduser.Id);     
36      }      
37   }
38}

MyDomainDiscLoginDefaultHandler クラスのテストクラス

MyDomainDiscoveryLoginHandler のテストクラスを次に示します。テストが機能するには、組織の [私のドメイン] ログインページ種別が [検出] に設定されている必要があります。

1// Test class for MyDomainDiscLoginDefaultHandler
2@isTest
3class MyDomainDiscLoginDefaultHandlerTest {
4    
5    /* Test Discoverable handler login. 
6       Create a user with specific email identifier and invoke login. 
7       Expected : User should be discovered and pagereference should be returned. 
8     */
9    @isTest static void testLogin() {
10        // Create user
11        String identifierEmail = getUniqueName() + '@test.org';
12        createTestUser(identifierEmail);
13        Map<StringString> requestAttributes = new Map<StringString>();
14        String startUrl = '';
15        MyDomainDiscLoginDefaultHandler myDomainDiscLoginDefaultHandler = new MyDomainDiscLoginDefaultHandler();
16        // Invoke login method from handler with the email of user created
17        PageReference  pageReference = myDomainDiscLoginDefaultHandler.login(identifierEmailstartUrlrequestAttributes);
18        // Asser page reference is returned
19        System.assertNotEquals(nullpageReference'Page reference was not returned');
20    }   
21    
22    /* Test Discoverable handler login with invalid (non-existing) user. 
23        Expected : Auth.LoginDiscoveryException  
24     */
25    @isTest static void testLoginWithInvalidUser() {
26        try {
27            Map<StringString> requestAttributes = new Map<StringString>();
28            String startUrl = '';
29            String uniqueName = getUniqueName();
30            String email = uniqueName + '@test.org';
31            MyDomainDiscLoginDefaultHandler myDomainDiscLoginDefaultHandler = new MyDomainDiscLoginDefaultHandler();
32            // Invoke login method from handler with non-existing user
33            myDomainDiscLoginDefaultHandler.login(emailstartUrlrequestAttributes);
34        }catch (Auth.LoginDiscoveryException loginDiscoveryException) {
35            // Assert exception message
36            System.assert(loginDiscoveryException.getMessage().contains('No unique user found')'message=' + loginDiscoveryException.getMessage());
37        }
38    }
39    
40    /*
41       Generate a random name
42     */
43    private static String getUniqueName() { 
44        String orgId = UserInfo.getOrganizationId();
45        String dateString = String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','');
46        Integer randomInt = Integer.valueOf(math.rint(math.random()*1000000));
47        String uniqueName = orgId + dateString + randomInt;
48        return uniqueName;
49    }
50    
51    /*
52      Create user with given email.
53     */
54    private static void createTestUser(String identifierEmail)
55    {
56        String uniqueName = getUniqueName();
57        Profile pf = [SELECT Id FROM Profile WHERE Name='Standard User'];
58        String profileID = pf.Id;
59        String fName = 'fname';
60        String lName = uniqueName + '-lname';            
61        User tuser = new User(  firstname = fName,
62                                lastName = lName,
63                                email = identifierEmail,
64                                Username = uniqueName + '@test.org',
65                                EmailEncodingKey = 'ISO-8859-1',
66                                Alias = uniqueName.substring(1823),
67                                TimeZoneSidKey = 'America/Los_Angeles',
68                                LocaleSidKey = 'en_US',
69                                LanguageLocaleKey = 'en_US',
70                                ProfileId = profileID);
71        insert tuser;
72    }
73}