在 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
  4. 選擇 Firebase 身份驗證庫。
  5. 完成後,Xcode 將自動開始在後台解析並下載您的依賴項。

將 Google 登錄 SDK 添加到您的項目

  1. 在 Xcode 中,打開應用程序項目,導航至File > Add Packages

  2. 出現提示時,添加 Google Sign-In SDK 存儲庫:

    https://github.com/google/GoogleSignIn-iOS
    
  3. 完成後,Xcode 將自動開始在後台解析並下載您的依賴項。

為您的 Firebase 項目啟用 Google 登錄

要允許用戶使用 Google Sign-In 登錄,您必須首先為您的 Firebase 項目啟用 Google Sign-In 提供程序:

  1. Firebase 控制台中,打開“身份驗證”部分。
  2. 登錄方法選項卡上,啟用Google提供商。
  3. 單擊“保存”

  4. 下載項目的GoogleService-Info.plist文件的新副本並將其複製到您的 Xcode 項目。用新版本覆蓋任何現有版本。 (請參閱將 Firebase 添加到您的 iOS 項目。)

導入需要的頭文件

首先,您必須將 Firebase SDK 和 Google Sign-In SDK 頭文件導入到您的應用中。

迅速

import FirebaseCore
import FirebaseAuth
import GoogleSignIn

Objective-C

@import FirebaseCore;
@import GoogleSignIn;

實施 Google 登錄

按照以下步驟實施 Google 登錄。有關在 iOS 上使用Google 登錄的詳細信息,請參閱 Google 登錄開發人員文檔

  1. 將自定義 URL 方案添加到您的 Xcode 項目:
    1. 打開您的項目配置:單擊左側樹視圖中的項目名稱。從“目標”部分選擇您的應用程序,然後選擇“信息”選項卡,並展開“URL 類型”部分。
    2. 單擊+按鈕,並為反向客戶端 ID 添加 URL 方案。要查找此值,請打開GoogleService-Info.plist配置文件,然後查找REVERSED_CLIENT_ID鍵。複製該鍵的值,並將其粘貼到配置頁面上的URL 方案框中。保持其他字段不變。

      完成後,您的配置應類似於以下內容(但具有特定於應用程序的值):

  2. 在應用程序委託的application:didFinishLaunchingWithOptions:方法中,配置FirebaseApp對象。

    迅速

    FirebaseApp.configure()
    

    Objective-C

    // Use Firebase library to configure APIs
    [FIRApp configure];
    
  3. 實現應用程序委託的application:openURL:options:方法。該方法應調用GIDSignIn實例的handleURL方法,該方法將正確處理應用程序在身份驗證過程結束時收到的 URL。

    迅速

    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 身份驗證憑據:

    迅速

    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. 可選:如果您想自定義按鈕,請執行以下操作:

    迅速

    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 登錄過程。

迅速

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 實時數據庫和雲存儲安全規則中,您可以從auth變量獲取登錄用戶的唯一用戶 ID,並使用它來控制用戶可以訪問哪些數據。

您可以通過將身份驗證提供程序憑據鏈接到現有用戶帳戶,允許用戶使用多個身份驗證提供程序登錄您的應用程序。

要註銷用戶,請調用signOut:

迅速

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;
}

您可能還需要為所有身份驗證錯誤添加錯誤處理代碼。請參閱處理錯誤