您可以將 Firebase Authentication 與自訂驗證系統整合,方法是修改驗證伺服器,在使用者成功登入時產生自訂簽署權杖。應用程式收到這個權杖後,會使用該權杖向 Firebase 進行驗證。
事前準備
- 建立 Firebase 專案並註冊應用程式 (如果尚未完成)。
-
使用 Swift Package Manager 安裝及管理 Firebase 依附元件。
- 在 Xcode 中保持開啟應用程式專案,然後依序點選「File」(檔案) 和「Add Packages」(新增 Package)。
- 系統提示時,請新增 Firebase Apple 平台 SDK 存放區:
- 選擇 Firebase Authentication 程式庫。
- 在目標建構設定的「Other Linker Flags」部分,新增
-ObjC標記。 - 完成後,Xcode 會自動開始在背景解析及下載依附元件。
https://github.com/firebase/firebase-ios-sdk.git
- 取得專案的伺服器金鑰:
-
在 Firebase 控制台中,依序前往「
Settings」(設定) >「 Service accounts」(服務帳戶) 分頁。 - 在「Firebase Admin SDK」部分底部,按一下「Generate New Private Key」(產生新的私密金鑰)。
- 新服務帳戶的公開/私密金鑰組會自動儲存至您的電腦。將這個檔案複製到驗證伺服器。
-
在 Firebase 控制台中,依序前往「
使用 Firebase 驗證
- 在
UIApplicationDelegate中匯入FirebaseCore模組,以及應用程式委派使用的任何其他 Firebase 模組。舉例來說,如要使用 Cloud Firestore 和 Authentication:SwiftUI
import SwiftUI import FirebaseCore import FirebaseFirestore import FirebaseAuth // ...
Swift
import FirebaseCore import FirebaseFirestore import FirebaseAuth // ...
Objective-C
@import FirebaseCore; @import FirebaseFirestore; @import FirebaseAuth; // ...
- 在應用程式委派的
application(_:didFinishLaunchingWithOptions:)方法中,設定FirebaseApp共用例項:SwiftUI
// Use Firebase library to configure APIs FirebaseApp.configure()
Swift
// Use Firebase library to configure APIs FirebaseApp.configure()
Objective-C
// Use Firebase library to configure APIs [FIRApp configure];
- 如果您使用 SwiftUI,則必須建立應用程式委派,並透過
UIApplicationDelegateAdaptor或NSApplicationDelegateAdaptor將其附加至App結構。您也必須停用應用程式委派物件重組。詳情請參閱 SwiftUI 操作說明。SwiftUI
@main struct YourApp: App { // register app delegate for Firebase setup @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate var body: some Scene { WindowGroup { NavigationView { ContentView() } } } }
- 使用者登入應用程式時,請將他們的登入憑證 (例如使用者名稱和密碼) 傳送至驗證伺服器。伺服器會檢查憑證,如果憑證有效,就會傳回自訂權杖 。
- 從驗證伺服器收到自訂權杖後,請將其傳遞至
signInWithCustomToken,讓使用者登入:Swift
Auth.auth().signIn(withCustomToken: customToken ?? "") { user, error in // ... }
Objective-C
[[FIRAuth auth] signInWithCustomToken:customToken completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { // ... }];
後續步驟
使用者首次登入後,系統會建立新的使用者帳戶,並連結至使用者登入時使用的憑證,也就是使用者名稱和密碼、電話號碼或驗證供應商資訊。這個新帳戶會儲存為 Firebase 專案的一部分,無論使用者如何登入,都可用來識別專案中所有應用程式的使用者。
在 Firebase Realtime Database 和 Cloud Storage 安全性規則中,您可以從
auth變數取得已登入使用者的專屬使用者 ID,並用來控管使用者可存取的資料。
您可以將驗證供應商憑證連結至現有使用者帳戶,允許使用者透過多個驗證供應商登入應用程式。
如要將使用者登出,請呼叫
signOut:。
Swift
let firebaseAuth = Auth.auth() do { try firebaseAuth.signOut() } catch let signOutError as NSError { print("Error signing out: %@", signOutError) }
Objective-C
NSError *signOutError; BOOL status = [[FIRAuth auth] signOut:&signOutError]; if (!status) { NSLog(@"Error signing out: %@", signOutError); return; }
您也可以為所有驗證錯誤新增錯誤處理程式碼。請參閱「處理錯誤」。