トークン交換ハンドラー Apex クラスの作成
トークン交換ハンドラーは、Oauth2TokenExchangeHandler 抽象クラスを拡張する Apex クラスとトークン交換ハンドラー定義で構成されます。まず、ハンドラ定義で参照する Apex クラスを作成します。
必要なエディション
| 使用可能なエディション: Enterprise Edition、Performance Edition、Unlimited Edition、および Developer Edition |
メモ [設定] でハンドラを定義するときに Apex クラス テンプレートを自動生成することで、このステップをスキップできます。自動生成されたハンドラーをカスタマイズしてください。
- [設定] から、[クイック検索] ボックスに「Apex」と入力し、[Apex クラス] を選択します。
- [新規] をクリックします。
-
Auth.Oauth2TokenExchangeHandlerabstract クラスを拡張する Apex クラスを作成します。abstract クラスは次のようになります。これには 2 つのメソッドが含まれます。最初の方法を使用して、ID プロバイダーからの受信トークンを検証します。2 番目の方法を使用して、トークンの件名を Salesforce ユーザーに対応付けます。//Abstract Class that a developer must extend for a token exchange handler global abstract class Oauth2TokenExchangeHandler { //First method called in the handler //This method must be overriden by the extending class global virtual Auth.TokenValidationResult validateIncomingToken(String appDeveloperName, Auth.IntegratingAppType appType, String incomingToken, Auth.OAuth2TokenExchangeType tokenType) return null; } //Second method called in the handler //This method must be overriden by the extending class global virtual User getUserForTokenSubject(Id networkId, Auth.TokenValidationResult result, Boolean canCreateUser, String appDeveloperName, Auth.IntegratingAppType appType) { return null; } }Auth.Oauth2TokenExchangeHandlerabstract クラスを拡張する実装例を次に示します。
重要 このコードサンプルはデモ用です。開始点として使用しますが、必ず慎重に評価、カスタマイズ、テストしてください。/*Token Exchange Handler Implementation Example*/ public class MyTokenExchangeClass extends Auth.Oauth2TokenExchangeHandler{ public override Auth.TokenValidationResult validateIncomingToken(String appDeveloperName, Auth.IntegratingAppType appType, String incomingToken, Auth.OAuth2TokenExchangeType tokenType) { //Depending on your incoming token, you validate it in different ways //If the incoming token is an opaque access token or refresh token, validate it with a callout to the identity provider //If it is a SAML assertion, validate it by checking the XML //If it is an ID Token or JWT, try using our JWT validation methods //The example below assumes that the incoming token is a JWT and that there is a public keys endpoint on the identity provider //Be very careful with any logic in this method and test carefully before using Boolean isValid = false; Auth.JWT jwt; //Custom data structure CustomStructuredUserData customData; //Standard user data structure Auth.UserData userData; if (tokenType == Auth.OAuth2TokenExchangeType.JWT || tokenType == Auth.OAuth2TokenExchangeType.ID_TOKEN) { try { jwt = Auth.JWTUtil.validateJWTWithKeysEndpoint(incomingToken, 'https://your-idp.com/keys', true); isValid = true; //These values would be sourced from the JWT or ID Token userData = new Auth.UserData('identifier', 'firstName', 'lastName', 'fullName', 'customer@email.com', 'link url', 'remote username', 'local', 'Provider (IDP Name)', '', new Map<String,String>()); //You can also pass data as generic object customData = new CustomStructuredUserData(); } catch (Exception e) { isValid = false; } } else if (tokenType == Auth.OAuth2TokenExchangeType.ACCESS_TOKEN || tokenType == Auth.OAuth2TokenExchangeType.REFRESH_TOKEN) { //Logic for validating a opaque access token or refresh token can go here //This validation typically involves a callout to the introspect or user info endpoints //If you call out to the user info endpoint, make sure to pass the data from the validation into the getUserForTokenSubject method using an Apex class or the user data class isValid = false; } else if (tokenType == Auth.OAuth2TokenExchangeType.SAML_2) { //Logic for validating a SAML assertion can go here //This validation involves XML parsing isValid = false; } else { //You can add new token types. If you don’t know how to validate the token, always check the type and return false isValid = false; } if(isValid){ return new Auth.TokenValidationResult(true, (object)customData, userData, incomingToken, tokenType, 'CustomErrorMessage'); } else { return new Auth.TokenValidationResult(isValid); } } public override User getUserForTokenSubject(Id networkId, Auth.TokenValidationResult result, Boolean canCreateUser, String appDeveloperName, Auth.IntegratingAppType appType) { //If you passed data from the validation method, grab it now. Remember to cast back for the custom data CustomStructuredUserData customData = (CustomStructuredUserData)result.data; Auth.UserData userData = result.userData; //If you don’t have any data from the token, you can perform a callout using the incoming token String userToken = result.token; //Now, search for a user User u; try { u = [SELECT Id, IsActive FROM User WHERE email =: userData.email]; } catch (Exception e) { //No user existed for this email address, or there were too many. Try looking harder } // If you didn’t find a user, check to see if you can create one if (canCreateUser && (u == null)) { u = new User(); u.firstName = userData.firstName; u.lastName = userData.lastName; //... Finish setting user attributes. For external users, make sure you set up the contact/account/person account //If you assign permission sets, do it in a future method to avoid mixed DML //Returning the user from this method handles the insertion, so it’s not necessary to manually insert } return u; } //This class gives you a way to pass stuctured data between the validateIncomingToken and getUserForTokenSubject methods //This example is for demonstration only. Implement this class in a way that matches the data that you are passing private class CustomStructuredUserData { public String customAttribute1; public Integer customAttribute2; public Map<String,Object> customAttribute3; } } - クラスを保存します。
- 準備ができたら、クラスの検証と件名の対応付けの方法をカスタマイズします。開発プロセスによっては、ハンドラーの作成を完了した後にこのステップを完了できます。
ハンドラの作成を終了するには、トークン交換ハンドラを定義します。[設定] でハンドラーを定義するか、メタデータ API を使用できます。
Apex ハンドラのカスタマイズの詳細については、次のリソースを参照してください。
- Apex 開発者ガイド: OAuth 2.0 トークン交換ハンドラの例
- Apex リファレンスガイド: Oauth2TokenExchangeHandler クラス
- Apex リファレンスガイド: TokenValidationResult クラス
- Apex リファレンスガイド: JWTUtil クラス
- Apex リファレンスガイド: OAuth2TokenExchangeType Enum
- Apex リファレンスガイド: IntegratingAppType Enum
この記事で問題は解決されましたか?
ご意見をお待ちしております。
