您可以將 Facebook 登入或 Facebook 有限登入功能整合至應用程式,讓使用者使用 Facebook 帳戶驗證 Firebase。
事前準備
使用 Swift Package Manager 安裝及管理 Firebase 依附元件。
- 在 Xcode 中保持開啟應用程式專案,然後依序點選「File」>「Add Packages」。
- 系統提示時,請新增 Firebase Apple 平台 SDK 存放區:
- 選擇 Firebase Authentication 程式庫。
- 將
-ObjC
標記新增至目標的建構設定「Other Linker Flags」部分。 - 完成後,Xcode 就會自動開始在背景中解析並下載依附元件。
https://github.com/firebase/firebase-ios-sdk.git
接下來,請執行一些設定步驟:
- 在 Facebook 開發人員網站上取得應用程式的 應用程式 ID 和 應用程式密鑰。
- 啟用 Facebook 登入功能:
- 在 Firebase 控制台中,開啟「Auth」部分。
- 在「登入方式」分頁中,啟用 Facebook 登入方式,並指定您從 Facebook 取得的「應用程式 ID」和「應用程式密鑰」。
- 接著,請確認您的 OAuth 重新導向 URI (例如
my-app-12345.firebaseapp.com/__/auth/handler
) 列為 Facebook 應用程式設定頁面 (Facebook for Developers 網站) 產品設定 > Facebook 登入 設定中的其中一個 OAuth 重新導向 URI。
實作 Facebook 登入功能
如要使用「傳統」Facebook 登入功能,請完成下列步驟。您也可以使用 Facebook 有限登入功能,詳情請參閱下一節。
- 按照
開發人員說明文件的說明,將 Facebook 登入整合至應用程式。初始化
FBSDKLoginButton
物件時,請設定委派作業,以便接收登入和登出事件。例如:let loginButton = FBSDKLoginButton() loginButton.delegate = self
FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init]; loginButton.delegate = self;
didCompleteWithResult:error:
。func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) { if let error = error { print(error.localizedDescription) return } // ... }
- (void)loginButton:(FBSDKLoginButton *)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error { if (error == nil) { // ... } else { NSLog(error.localizedDescription); } }
- 在
UIApplicationDelegate
中匯入FirebaseCore
模組,以及應用程式委派程式使用的任何其他 Firebase 模組。例如,如要使用 Cloud Firestore 和 Authentication:import SwiftUI import FirebaseCore import FirebaseFirestore import FirebaseAuth // ...
import FirebaseCore import FirebaseFirestore import FirebaseAuth // ...
@import FirebaseCore; @import FirebaseFirestore; @import FirebaseAuth; // ...
- 在應用程式委派作業的
application(_:didFinishLaunchingWithOptions:)
方法中,設定FirebaseApp
共用例項:// Use Firebase library to configure APIs FirebaseApp.configure()
// Use Firebase library to configure APIs FirebaseApp.configure()
// Use Firebase library to configure APIs [FIRApp configure];
- 如果您使用 SwiftUI,則必須建立應用程式委派程式,並透過
UIApplicationDelegateAdaptor
或NSApplicationDelegateAdaptor
將其附加至App
結構體。您也必須停用應用程式委派程式 swizzling。詳情請參閱 SwiftUI 操作說明。@main struct YourApp: App { // register app delegate for Firebase setup @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate var body: some Scene { WindowGroup { NavigationView { ContentView() } } } }
- 使用者成功登入後,在
didCompleteWithResult:error:
的實作中,請取得已登入使用者的存取權杖,然後換取 Firebase 憑證:let credential = FacebookAuthProvider .credential(withAccessToken: AccessToken.current!.tokenString)
FIRAuthCredential *credential = [FIRFacebookAuthProvider credentialWithAccessToken:[FBSDKAccessToken currentAccessToken].tokenString];
實作 Facebook 限制登入
如要使用 Facebook 限制登入功能,而非「傳統」Facebook 登入功能,請完成下列步驟。
- 按照 開發人員說明文件的說明,將 Facebook 有限登入功能整合至應用程式。
- 針對每項登入要求,產生一個專屬的隨機字串 (稱為「Nonce」),您可以使用這項字串,確保您取得的 ID 權杖是專門針對應用程式的驗證要求核發。這個步驟對於防範重送攻擊至關重要。您可以使用
SecRandomCopyBytes(_:_:_)
產生加密編譯安全的 Nonce,如以下範例所示:private 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) }
// 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]; }
@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 }
- (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
,並附加 Nonce。例如:func setupLoginButton() { let nonce = randomNonceString() currentNonce = nonce loginButton.delegate = self loginButton.loginTracking = .limited loginButton.nonce = sha256(nonce) }
- (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:
。func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) { if let error = error { print(error.localizedDescription) return } // ... }
- (void)loginButton:(FBSDKLoginButton *)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error { if (error == nil) { // ... } else { NSLog(error.localizedDescription); } }
- 在
UIApplicationDelegate
中匯入FirebaseCore
模組,以及應用程式委派程式使用的任何其他 Firebase 模組。例如,如要使用 Cloud Firestore 和 Authentication:import SwiftUI import FirebaseCore import FirebaseFirestore import FirebaseAuth // ...
import FirebaseCore import FirebaseFirestore import FirebaseAuth // ...
@import FirebaseCore; @import FirebaseFirestore; @import FirebaseAuth; // ...
- 在應用程式委派作業的
application(_:didFinishLaunchingWithOptions:)
方法中,設定FirebaseApp
共用例項:// Use Firebase library to configure APIs FirebaseApp.configure()
// Use Firebase library to configure APIs FirebaseApp.configure()
// Use Firebase library to configure APIs [FIRApp configure];
- 如果您使用 SwiftUI,則必須建立應用程式委派程式,並透過
UIApplicationDelegateAdaptor
或NSApplicationDelegateAdaptor
將其附加至App
結構體。您也必須停用應用程式委派程式 swizzling。詳情請參閱 SwiftUI 操作說明。@main struct YourApp: App { // register app delegate for Firebase setup @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate var body: some Scene { WindowGroup { NavigationView { ContentView() } } } }
- 使用者成功登入後,在
didCompleteWithResult:error:
的實作中,請使用 Facebook 回應中的 ID 權杖,搭配未經雜湊處理的 Nonce 取得 Firebase 憑證:// Initialize a Firebase credential. let idTokenString = AuthenticationToken.current?.tokenString let nonce = currentNonce let credential = OAuthProvider.credential(withProviderID: "facebook.com", idToken: idTokenString!, rawNonce: nonce)
// Initialize a Firebase credential. NSString *idTokenString = FBSDKAuthenticationToken.currentAuthenticationToken.tokenString; NSString *rawNonce = self.currentNonce; FIROAuthCredential *credential = [FIROAuthProvider credentialWithProviderID:@"facebook.com" IDToken:idTokenString rawNonce:rawNonce];
使用 Firebase 進行驗證
最後,請使用 Firebase 憑證向 Firebase 進行驗證:
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 // ... }
[[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; // ... }];
後續步驟
使用者首次登入後,系統會建立新使用者帳戶,並連結至使用者登入時所用的憑證 (即使用者名稱和密碼、電話號碼或驗證服務提供者資訊)。這個新帳戶會儲存在 Firebase 專案中,無論使用者如何登入,都可以用於在專案中的每個應用程式中識別使用者。
在 Firebase Realtime Database 和 Cloud Storage 安全性規則中,您可以從
auth
變數取得已登入使用者的專屬使用者 ID,並利用該 ID 控管使用者可存取的資料。
您可以將驗證服務供應商憑證連結至現有使用者帳戶,讓使用者使用多個驗證服務供應商登入應用程式。
如要讓使用者登出,請呼叫
signOut:
。
let firebaseAuth = Auth.auth() do { try firebaseAuth.signOut() } catch let signOutError as NSError { print("Error signing out: %@", signOutError) }
NSError *signOutError; BOOL status = [[FIRAuth auth] signOut:&signOutError]; if (!status) { NSLog(@"Error signing out: %@", signOutError); return; }
您可能還想為各種驗證錯誤新增錯誤處理程式碼。請參閱「處理錯誤」。