在 Apple 平台上使用 Google 登入功能進行驗證

您可以讓使用者透過自己的 Google 帳戶,以 Firebase 進行驗證,步驟如下: 將 Google 登入整合至您的應用程式

事前準備

使用 Swift Package Manager 安裝及管理 Firebase 依附元件。

  1. 在 Xcode 中保持開啟應用程式專案,然後依序選擇 [檔案] >新增套件
  2. 在系統提示時,新增 Firebase Apple 平台 SDK 存放區:
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. 選擇 Firebase 驗證資料庫。
  5. 在目標建構設定的「Other Linker Flags」部分中新增 -ObjC 標記。
  6. 完成後,Xcode 會自動開始解析並下載 複製到背景依附元件

將 Google Sign-In SDK 新增至專案

  1. 在 Xcode 中保持開啟應用程式專案,然後依序選擇 [檔案] >新增套件

  2. 在系統提示時,新增 Google Sign-In SDK 存放區:

    https://github.com/google/GoogleSignIn-iOS
    
  3. 完成後,Xcode 會自動開始解析並下載 複製到背景依附元件

為 Firebase 專案啟用 Google 登入功能

如要允許使用者使用 Google 登入功能登入,您必須先啟用 Firebase 專案的 Google 登入供應商:

  1. Firebase 控制台開啟「驗證」專區。
  2. 在「Sign in method」分頁中,啟用「Google」供應商。
  3. 按一下 [儲存]

  4. 下載新的專案 GoogleService-Info.plist 檔案副本,然後 複製到 Xcode 專案使用新版本覆寫任何現有版本 第一項。(請參閱「將 Firebase 新增至 iOS) 專案)。

匯入必要的標頭檔案

首先,您必須將 Firebase SDK 和 Google Sign-In SDK 標頭檔案匯入至

Swift

import FirebaseCore
import FirebaseAuth
import GoogleSignIn

Objective-C

@import FirebaseCore;
@import GoogleSignIn;

設定 Google 登入

請按照以下步驟實作 Google 登入功能。請參閱 Google 登入 開發人員說明文件,進一步瞭解如何使用 Google 透過 iOS 登入。

  1. 在 Xcode 專案中新增自訂網址配置:
    1. 開啟專案設定:按一下左側樹狀結構中的專案名稱 檢視畫面。從「目標」部分中選取應用程式,然後 選取「資訊」分頁標籤,然後展開「網址類型」部分。
    2. 按一下 + 按鈕,然後新增反向網址配置 用戶端 ID。如要找出這個值,請開啟 GoogleService-Info.plist 設定檔,找出 REVERSED_CLIENT_ID 鍵。複製該鍵的值 並將其貼到設定頁面的 [URL 配置] 方塊中。 其他欄位則維持不變。

      設定完成後,設定看起來應該會與 後面 (但採用您應用程式的專屬值):

  2. 在應用程式委派的 application:didFinishLaunchingWithOptions: 中 方法,設定 FirebaseApp 物件。

    Swift

    FirebaseApp.configure()
    

    Objective-C

    // Use Firebase library to configure APIs
    [FIRApp configure];
    
  3. 實作應用程式的 application:openURL:options: 方法 委派。此方法應呼叫handleURL GIDSignIn 例項,可妥善處理 應用程式會在驗證程序結束時收到。

    Swift

    func application(_ app: UIApplication,
                     open url: URL,
                     options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
      return GIDSignIn.sharedInstance.handle(url)
    }
    

    Objective-C

    - (BOOL)application:(nonnull UIApplication *)application
                openURL:(nonnull NSURL *)url
                options:(nonnull NSDictionary<NSString *, id> *)options {
      return [[GIDSignIn sharedInstance] handleURL:url];
    }
    
  4. 將顯示畫面控制器和應用程式的用戶端 ID 傳遞至 Google 登入供應商的 signIn 方法並建立 Firebase 產生的 Google 驗證權杖驗證憑證:

    Swift

    guard let clientID = FirebaseApp.app()?.options.clientID else { return }
    
    // Create Google Sign In configuration object.
    let config = GIDConfiguration(clientID: clientID)
    GIDSignIn.sharedInstance.configuration = config
    
    // Start the sign in flow!
    GIDSignIn.sharedInstance.signIn(withPresenting: self) { [unowned self] result, error in
      guard error == nil else {
        // ...
      }
    
      guard let user = result?.user,
        let idToken = user.idToken?.tokenString
      else {
        // ...
      }
    
      let credential = GoogleAuthProvider.credential(withIDToken: idToken,
                                                     accessToken: user.accessToken.tokenString)
    
      // ...
    }
    

    Objective-C

    GIDConfiguration *config = [[GIDConfiguration alloc] initWithClientID:[FIRApp defaultApp].options.clientID];
    [GIDSignIn.sharedInstance setConfiguration:config];
    
    __weak __auto_type weakSelf = self;
    [GIDSignIn.sharedInstance signInWithPresentingViewController:self
          completion:^(GIDSignInResult * _Nullable result, NSError * _Nullable error) {
      __auto_type strongSelf = weakSelf;
      if (strongSelf == nil) { return; }
    
      if (error == nil) {
        FIRAuthCredential *credential =
        [FIRGoogleAuthProvider credentialWithIDToken:result.user.idToken.tokenString
                                         accessToken:result.user.accessToken.tokenString];
        // ...
      } else {
        // ...
      }
    }];
    
    
  5. GIDSignInButton 新增至分鏡腳本、XIB 檔案,或 以程式輔助方式例項化。將按鈕新增至分鏡腳本或 XIB 檔案後,請新增檢視畫面,並將自訂類別設為 GIDSignInButton
  6. 選用步驟:如要自訂按鈕,請執行 包括:

    Swift

    1. 在檢視控制器中,將登入按鈕宣告為屬性。
      @IBOutlet weak var signInButton: GIDSignInButton!
    2. 將按鈕連結至您剛才使用的 signInButton 屬性 宣告。
    3. 設定 GIDSignInButton 物件

    Objective-C

    1. 在檢視控制器的標頭檔案中,將登入按鈕宣告為 資源。
      @property(weak, nonatomic) IBOutlet GIDSignInButton *signInButton;
    2. 將按鈕連結至您剛才使用的 signInButton 屬性 宣告。
    3. 設定 GIDSignInButton 物件

透過 Firebase 驗證

最後,建立驗證憑證,完成 Firebase 登入程序

Swift

Auth.auth().signIn(with: credential) { result, error in

  // At this point, our 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;
  // ...
}];

後續步驟

使用者首次登入後,系統會建立新的使用者帳戶 也就是使用者的名稱和密碼 號碼或驗證提供者資訊,也就是使用者登入時使用的網址。這項新功能 帳戶儲存為 Firebase 專案的一部分,可用來識別 使用者登入專案中的所有應用程式

  • 在您的應用程式中,您可以透過 User 物件。請參閱管理使用者

  • 在您的 Firebase 即時資料庫和 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;
}

我們也建議您新增錯誤處理程式碼,適用於完整的驗證範圍 發生錯誤。請參閱處理錯誤