この文章は 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 global class MyDomainDiscLoginDefaultHandler implements Auth.MyDomainLoginDiscoveryHandler {
7 global PageReference login(String identifierString startUrlMap<StringString> requestAttributes) 
8{
9   if (identifier != null) {
10        // Search for user by email
11        List<User> users = [SELECT Id FROM User WHERE Email = :identifier AND IsActive = TRUE];
12        if (!users.isEmpty() && users.size() == 1) {
13            return discoveryResult(users[0]startUrlrequestAttributes);
14        } else {
15            throw new Auth.LoginDiscoveryException('No unique user found. User count=' + users.size());
16        }
17    }
18    throw new Auth.LoginDiscoveryException('Invalid Identifier');
19  }
20    private PageReference getSsoRedirect(User userString startUrlMap<StringString> requestAttributes) {
21    // 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:
22    // SamlSsoConfig SSO = [select Id from SamlSsoConfig where DeveloperName='SamlTest' limit 1];
23    // To get the URL for a My Domain subdomain, you can pass null in the communityURL parameter.    
24    // String ssoUrl = Auth.AuthConfiguration.getSamlSsoUrl(null, startUrl, SSO.Id);
25    // return new PageReference(ssoUrl);
26    return null;
27  }
28     private PageReference discoveryResult(User userString startUrlMap<StringString> requestAttributes) 
29     {
30     PageReference ssoRedirect = getSsoRedirect(userstartUrlrequestAttributes);
31      if (ssoRedirect != null) {
32        return ssoRedirect;
33      } 
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    /* Test Discoverable handler login.
5       Create a user with specific email identifier and invoke login.
6       Expected : User should be discovered and pagereference should be returned.
7     */
8    @isTest static void testLogin() {
9        // Create user
10        String identifierEmail = getUniqueName() + '@test.org';
11        createTestUser(identifierEmail);
12        Map<StringString> requestAttributes = new Map<StringString>();
13        String startUrl = '';
14        MyDomainDiscLoginDefaultHandler myDomainDiscLoginDefaultHandler = new MyDomainDiscLoginDefaultHandler();
15        // Invoke login method from handler with the email of user created
16        PageReference  pageReference = myDomainDiscLoginDefaultHandler.login(identifierEmailstartUrlrequestAttributes);
17        // Asser page reference is returned
18        System.assertNotEquals(nullpageReference'Page reference was not returned');
19    }
20    /* Test Discoverable handler login with invalid (non-existing) user.
21        Expected : Auth.LoginDiscoveryException
22     */
23    @isTest static void testLoginWithInvalidUser() {
24        try {
25            Map<StringString> requestAttributes = new Map<StringString>();
26            String startUrl = '';
27            String uniqueName = getUniqueName();
28            String email = uniqueName + '@test.org';
29            MyDomainDiscLoginDefaultHandler myDomainDiscLoginDefaultHandler = new MyDomainDiscLoginDefaultHandler();
30            // Invoke login method from handler with non-existing user
31            myDomainDiscLoginDefaultHandler.login(emailstartUrlrequestAttributes);
32        }catch (Auth.LoginDiscoveryException loginDiscoveryException) {
33            // Assert exception message
34            System.assert(loginDiscoveryException.getMessage().contains('No unique user found')'message=' + loginDiscoveryException.getMessage());
35        }
36    }
37    /*
38       Generate a random name
39     */
40    private static String getUniqueName() {
41        String orgId = UserInfo.getOrganizationId();
42        String dateString = String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','');
43        Integer randomInt = Integer.valueOf(math.rint(math.random()*1000000));
44        String uniqueName = orgId + dateString + randomInt;
45        return uniqueName;
46    }
47    /*
48      Create user with given email.
49     */
50    private static void createTestUser(String identifierEmail)
51    {
52        String uniqueName = getUniqueName();
53        Profile pf = [SELECT Id FROM Profile WHERE Name='Standard User'];
54        String profileID = pf.Id;
55        String fName = 'fname';
56        String lName = uniqueName + '-lname'
57        User tuser = new User(  firstname = fName,
58                                lastName = lName,
59                                email = identifierEmail,
60                                Username = uniqueName + '@test.org',
61                                EmailEncodingKey = 'ISO-8859-1',
62                                Alias = uniqueName.substring(1823),
63                                TimeZoneSidKey = 'America/Los_Angeles',
64                                LocaleSidKey = 'en_US',
65                                LanguageLocaleKey = 'en_US',
66                                ProfileId = profileID);
67        insert tuser;
68    }
69}