iOS で Facebook を使用したユーザーのログイン
Facebook ログインまたは Facebook 制限付きログインをアプリに統合すると、ユーザーが Facebook アカウントを使用して Identity Platform で認証できるようになります。このページでは、Identity Platform を使用して Facebook でログインを iOS アプリに追加する方法について説明します。
始める前に
- Podfileに次の Pod を含めます。- pod 'FirebaseAuth'
- コンソールの [ID プロバイダ] ページに移動します。 Google Cloud 
- [プロバイダを追加] をクリックします。 
- リストから [Facebook] を選択します。 
- Facebook のアプリ ID と App Secret を入力します。ID とシークレットをまだ持っていない場合は、デベロッパー向け Facebook ページから取得できます。 
- [Facebook を構成する] に表示されている URI を、Facebook アプリの有効な OAuth リダイレクト URI として構成します。Identity Platform でカスタム ドメインを構成した場合、デフォルト ドメインではなくカスタム ドメインを使用するように、Facebook アプリの構成でリダイレクト URI を更新します。たとえば、 - https://myproject.firebaseapp.com/__/auth/handlerを- https://auth.myownpersonaldomain.com/__/auth/handlerに変更します。
- [承認済みドメイン] で [ドメインを追加] をクリックして、アプリのドメインを登録します。開発目的の場合は、 - localhostはデフォルトですでに有効になっています。
- [アプリケーションの構成] で [詳細を設定] をクリックします。このスニペットをアプリのコードにコピーして、Identity Platform Client SDK を初期化します。 
- [保存] をクリックします。 
Facebook ログインを実装する
「クラシック」Facebook ログインを使用するには、次の手順を行います。または、Facebook 制限付きログインを使用することもできます。次のセクションをご覧ください。
- デベロッパー向けドキュメントに沿って Facebook ログインをアプリに統合します。FBSDKLoginButtonオブジェクトを初期化するときに、ログイン イベントとログアウト イベントを受信するようにデリゲートを設定します。次に例を示します。デリゲートでSwiftlet loginButton = FBSDKLoginButton() loginButton.delegate = self Objective-CFBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init]; loginButton.delegate = self; didCompleteWithResult:error:を実装します。Swiftfunc loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) { if let error = error { print(error.localizedDescription) return } // ... } Objective-C- (void)loginButton:(FBSDKLoginButton *)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error { if (error == nil) { // ... } else { NSLog(error.localizedDescription); } } 
- Firebase モジュールを UIApplicationDelegateにインポートします。Swiftimport FirebaseCore import FirebaseAuth Objective-C@import FirebaseCore; @import FirebaseAuth; 
- FirebaseApp共有インスタンスを構成します。通常はアプリの- application:didFinishLaunchingWithOptions:メソッドで行います。- Swift- // Use Firebase library to configure APIs FirebaseApp.configure() - Objective-C- // Use Firebase library to configure APIs [FIRApp configure]; 
- ユーザーがログインに成功したら、didCompleteWithResult:error:の実装で、ログインしたユーザーのアクセス トークンを取得し、Identity Platform の認証情報と交換します。Swiftlet credential = FacebookAuthProvider .credential(withAccessToken: AccessToken.current!.tokenString) Objective-CFIRAuthCredential *credential = [FIRFacebookAuthProvider credentialWithAccessToken:[FBSDKAccessToken currentAccessToken].tokenString]; 
Facebook 制限付きログインを実装する
「クラシック」Facebook ログインの代わりに Facebook 制限付きログインを使用するには、次の手順を行います。
- デベロッパー向けドキュメントに沿って Facebook 制限付きログインをアプリに統合します。
- ログイン リクエストごとに一意の文字列「ノンス」を生成します。ノンスは、取得した ID トークンが、アプリの認証リクエストへのレスポンスとして付与されたことを確認するために使用されます。この手順は、リプレイ攻撃の防止に重要です。SecRandomCopyBytes(_:_:_)を使用すると、iOS で暗号的に安全なノンスを生成できます。次に例を示します。ログイン リクエストでノンスの SHA-256 ハッシュを送信します。Facebook は、変更を加えることなく、レスポンスでこのノンスを渡します。Identity Platform は、元のノンスをハッシュ化し、Facebook から渡された値と比較することで、レスポンスを検証します。Swiftprivate func randomNonceString(length: Int = 32) -> String { precondition(length > 0) var randomBytes = [UInt8](repeating: 0, count: length) let errorCode = SecRandomCopyBytes(kSecRandomDefault, randomBytes.count, &randomBytes) if errorCode != errSecSuccess { fatalError( "Unable to generate nonce. SecRandomCopyBytes failed with OSStatus \(errorCode)" ) } let charset: [Character] = Array("0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._") let nonce = randomBytes.map { byte in // Pick a random character from the set, wrapping around if needed. charset[Int(byte) % charset.count] } return String(nonce) } Objective-C// Adapted from https://auth0.com/docs/api-auth/tutorials/nonce#generate-a-cryptographically-random-nonce - (NSString *)randomNonce:(NSInteger)length { NSAssert(length > 0, @"Expected nonce to have positive length"); NSString *characterSet = @"0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._"; NSMutableString *result = [NSMutableString string]; NSInteger remainingLength = length; while (remainingLength > 0) { NSMutableArray *randoms = [NSMutableArray arrayWithCapacity:16]; for (NSInteger i = 0; i < 16; i++) { uint8_t random = 0; int errorCode = SecRandomCopyBytes(kSecRandomDefault, 1, &random); NSAssert(errorCode == errSecSuccess, @"Unable to generate nonce: OSStatus %i", errorCode); [randoms addObject:@(random)]; } for (NSNumber *random in randoms) { if (remainingLength == 0) { break; } if (random.unsignedIntValue < characterSet.length) { unichar character = [characterSet characterAtIndex:random.unsignedIntValue]; [result appendFormat:@"%C", character]; remainingLength--; } } } return [result copy]; } Swift@available(iOS 13, *) private func sha256(_ input: String) -> String { let inputData = Data(input.utf8) let hashedData = SHA256.hash(data: inputData) let hashString = hashedData.compactMap { String(format: "%02x", $0) }.joined() return hashString } Objective-C- (NSString *)stringBySha256HashingString:(NSString *)input { const char *string = [input UTF8String]; unsigned char result[CC_SHA256_DIGEST_LENGTH]; CC_SHA256(string, (CC_LONG)strlen(string), result); NSMutableString *hashed = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2]; for (NSInteger i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) { [hashed appendFormat:@"%02x", result[i]]; } return hashed; } 
- FBSDKLoginButtonをセットアップする際に、ログイン イベントとログアウト イベントを受信するようにデリゲートを設定し、トラッキング モードを- FBSDKLoginTrackingLimitedに設定して、ノンスをアタッチします。次に例を示します。デリゲートで- Swift- func setupLoginButton() { let nonce = randomNonceString() currentNonce = nonce loginButton.delegate = self loginButton.loginTracking = .limited loginButton.nonce = sha256(nonce) } - Objective-C- - (void)setupLoginButton { NSString *nonce = [self randomNonce:32]; self.currentNonce = nonce; self.loginButton.delegate = self; self.loginButton.loginTracking = FBSDKLoginTrackingLimited self.loginButton.nonce = [self stringBySha256HashingString:nonce]; } - didCompleteWithResult:error:を実装します。- Swift- func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) { if let error = error { print(error.localizedDescription) return } // ... } - Objective-C- - (void)loginButton:(FBSDKLoginButton *)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error { if (error == nil) { // ... } else { NSLog(error.localizedDescription); } } 
- Firebase モジュールを UIApplicationDelegateにインポートします。Swiftimport Firebase Objective-C@import Firebase; 
- FirebaseApp共有インスタンスを構成します。通常はアプリの- application:didFinishLaunchingWithOptions:メソッドで行います。- Swift- // Use Firebase library to configure APIs FirebaseApp.configure() - Objective-C- // Use Firebase library to configure APIs [FIRApp configure]; 
- ユーザーがログインに成功したら、didCompleteWithResult:error:の実装で、Facebook のレスポンスの ID トークンと、ハッシュ化されていないノンスを組み合わせて使用して、Identity Platform の認証情報を取得します。Swift// Initialize an Identity Platform credential. let idTokenString = AuthenticationToken.current?.tokenString let nonce = currentNonce let credential = OAuthProvider.credential(withProviderID: "facebook.com", IDToken: idTokenString, rawNonce: nonce) Objective-C// Initialize an Identity Platform credential. NSString *idTokenString = FBSDKAuthenticationToken.currentAuthenticationToken.tokenString; NSString *rawNonce = self.currentNonce; FIROAuthCredential *credential = [FIROAuthProvider credentialWithProviderID:@"facebook.com" IDToken:idTokenString rawNonce:rawNonce]; 
Identity Platform で認証します
最後に、Identity Platform の認証情報を使用して Identity Platform で認証します。
Swift
Auth.auth().signIn(with: credential) { authResult, error in if let error = error { let authError = error as NSError if isMFAEnabled, authError.code == AuthErrorCode.secondFactorRequired.rawValue { // The user is a multi-factor user. Second factor challenge is required. let resolver = authError .userInfo[AuthErrorUserInfoMultiFactorResolverKey] as! MultiFactorResolver var displayNameString = "" for tmpFactorInfo in resolver.hints { displayNameString += tmpFactorInfo.displayName ?? "" displayNameString += " " } self.showTextInputPrompt( withMessage: "Select factor to sign in\n\(displayNameString)", completionBlock: { userPressedOK, displayName in var selectedHint: PhoneMultiFactorInfo? for tmpFactorInfo in resolver.hints { if displayName == tmpFactorInfo.displayName { selectedHint = tmpFactorInfo as? PhoneMultiFactorInfo } } PhoneAuthProvider.provider() .verifyPhoneNumber(with: selectedHint!, uiDelegate: nil, multiFactorSession: resolver .session) { verificationID, error in if error != nil { print( "Multi factor start sign in failed. Error: \(error.debugDescription)" ) } else { self.showTextInputPrompt( withMessage: "Verification code for \(selectedHint?.displayName ?? "")", completionBlock: { userPressedOK, verificationCode in let credential: PhoneAuthCredential? = PhoneAuthProvider.provider() .credential(withVerificationID: verificationID!, verificationCode: verificationCode!) let assertion: MultiFactorAssertion? = PhoneMultiFactorGenerator .assertion(with: credential!) resolver.resolveSignIn(with: assertion!) { authResult, error in if error != nil { print( "Multi factor finanlize sign in failed. Error: \(error.debugDescription)" ) } else { self.navigationController?.popViewController(animated: true) } } } ) } } } ) } else { self.showMessagePrompt(error.localizedDescription) return } // ... return } // User is signed in // ... }
Objective-C
[[FIRAuth auth] signInWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { if (isMFAEnabled && error && error.code == FIRAuthErrorCodeSecondFactorRequired) { FIRMultiFactorResolver *resolver = error.userInfo[FIRAuthErrorUserInfoMultiFactorResolverKey]; NSMutableString *displayNameString = [NSMutableString string]; for (FIRMultiFactorInfo *tmpFactorInfo in resolver.hints) { [displayNameString appendString:tmpFactorInfo.displayName]; [displayNameString appendString:@" "]; } [self showTextInputPromptWithMessage:[NSString stringWithFormat:@"Select factor to sign in\n%@", displayNameString] completionBlock:^(BOOL userPressedOK, NSString *_Nullable displayName) { FIRPhoneMultiFactorInfo* selectedHint; for (FIRMultiFactorInfo *tmpFactorInfo in resolver.hints) { if ([displayName isEqualToString:tmpFactorInfo.displayName]) { selectedHint = (FIRPhoneMultiFactorInfo *)tmpFactorInfo; } } [FIRPhoneAuthProvider.provider verifyPhoneNumberWithMultiFactorInfo:selectedHint UIDelegate:nil multiFactorSession:resolver.session completion:^(NSString * _Nullable verificationID, NSError * _Nullable error) { if (error) { [self showMessagePrompt:error.localizedDescription]; } else { [self showTextInputPromptWithMessage:[NSString stringWithFormat:@"Verification code for %@", selectedHint.displayName] completionBlock:^(BOOL userPressedOK, NSString *_Nullable verificationCode) { FIRPhoneAuthCredential *credential = [[FIRPhoneAuthProvider provider] credentialWithVerificationID:verificationID verificationCode:verificationCode]; FIRMultiFactorAssertion *assertion = [FIRPhoneMultiFactorGenerator assertionWithCredential:credential]; [resolver resolveSignInWithAssertion:assertion completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { if (error) { [self showMessagePrompt:error.localizedDescription]; } else { NSLog(@"Multi factor finanlize sign in succeeded."); } }]; }]; } }]; }]; } else if (error) { // ... return; } // User successfully signed in. Get user data from the FIRUser object if (authResult == nil) { return; } FIRUser *user = authResult.user; // ... }];
次のステップ
- Identity Platform ユーザーの詳細について確認する。
- 他の ID プロバイダでユーザーのログインを行う。