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

您將 Google 登入整合至您的應用程式後,即可讓使用者利用他們的 Google 帳戶,向 Firebase 進行驗證。

事前準備

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

  1. 在 Xcode 中保持開啟應用程式專案,然後依序點選「File」>「Add Packages」
  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 中保持開啟應用程式專案,然後依序點選「File」>「Add Packages」

  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. 點選「Save」

  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 登入功能。如要進一步瞭解如何透過 iOS 裝置使用 Google 登入,請參閱 Google 登入開發人員說明文件

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

      設定完成後,設定看起來應類似下列內容 (但會使用您的應用程式專屬值):

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

    Swift

    FirebaseApp.configure()
    

    Objective-C

    // Use Firebase library to configure APIs
    [FIRApp configure];
    
  3. 實作應用程式委派的 application:openURL:options: 方法。此方法應呼叫 GIDSignIn 執行個體的 handleURL 方法,該方法可正確處理應用程式在驗證程序結束時接收的網址。

    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 方法,然後透過產生的 Google 驗證權杖建立 Firebase 驗證憑證:

    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,並使用該 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;
}

您可能也想要針對各種驗證錯誤加入錯誤處理程式碼。請參閱處理錯誤