Google ログインをアプリに統合することで、ユーザーは Firebase での認証に Google アカウントを使用できるようになります。
始める前に
- Apple プロジェクトに Firebase を追加します。
Podfile
に次の Pod を含めます。pod 'FirebaseAuth' pod 'GoogleSignIn'
- アプリを Firebase プロジェクトに接続していない場合は、Firebase コンソールで接続します。
- Firebase コンソールで、ログイン方法として Google を有効にします。
- Firebase コンソールで [Authentication] セクションを開きます。
- [Sign in method] タブで [Google] を有効にし、[保存] をクリックします。
1. 必須ヘッダー ファイルをインポートする
まず Firebase SDK と Google ログイン SDK のヘッダー ファイルをアプリにインポートします。
Swift
import FirebaseCore import GoogleSignIn
Objective-C
@import FirebaseCore; @import GoogleSignIn;
2. Google ログインを実装する
Google ログインを実装する手順は次のとおりです。iOS で Google ログインを使用する方法について詳しくは、Google ログインに関するデベロッパー向けドキュメントをご覧ください。
- Xcode プロジェクトにカスタム URL スキームを追加します。
- プロジェクト構成を開きます(左側のツリービューでプロジェクト名をダブルクリックします)。[TARGETS] セクションでアプリを選択し、[Info] タブを開いて [URL Types] セクションを展開します。
- [+] ボタンをクリックし、反転クライアント ID の URL スキームを追加します。この値を確認するには、
構成ファイルを開いてGoogleService-Info.plist REVERSED_CLIENT_ID
キーを探します。見つかったキーの値をコピーし、構成ページの [URL Schemes] ボックスに貼り付けます。その他の入力欄は空白にしておきます。完了すると、構成は次のようになります(ただし、値はアプリケーションによって異なります)。
- アプリのデリゲートの
application:didFinishLaunchingWithOptions:
メソッドで、FirebaseApp
オブジェクトを構成します。Swift
// Use Firebase library to configure APIs FirebaseApp.configure()
Objective-C
// Use Firebase library to configure APIs [FIRApp configure];
- アプリのデリゲートに
application:openURL:options:
メソッドを実装します。このメソッドはGIDSignIn
インスタンスのhandleURL
メソッドを呼び出します。これによって、認証プロセスの最後にアプリが受け取る URL が正しく処理されます。Swift
@available(iOS 9.0, *) func application(_ application: 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]; }
- アプリのプレゼンティング ビュー コントローラとクライアント ID を Google ログインのログイン メソッドに渡して、結果として得られる Google 認証トークンから Firebase 認証情報を作成します。
Swift
guard let clientID = FirebaseApp.app()?.options.clientID else { return } // Create Google Sign In configuration object. let config = GIDConfiguration(clientID: clientID) // Start the sign in flow! GIDSignIn.sharedInstance.signIn(with: config, presenting: self) { [unowned self] user, error in if let error = error { // ... return } guard let authentication = user?.authentication, let idToken = authentication.idToken else { return } let credential = GoogleAuthProvider.credential(withIDToken: idToken, accessToken: authentication.accessToken) // ... }
Objective-C
GIDConfiguration *config = [[GIDConfiguration alloc] initWithClientID:[FIRApp defaultApp].options.clientID]; __weak __auto_type weakSelf = self; [GIDSignIn.sharedInstance signInWithConfiguration:config presentingViewController:self callback:^(GIDGoogleUser * _Nullable user, NSError * _Nullable error) { __auto_type strongSelf = weakSelf; if (strongSelf == nil) { return; } if (error == nil) { GIDAuthentication *authentication = user.authentication; FIRAuthCredential *credential = [FIRGoogleAuthProvider credentialWithIDToken:authentication.idToken accessToken:authentication.accessToken]; // ... } else { // ... } }];
GIDSignInButton
をストーリーボードまたは XIB ファイルに追加するか、プログラムによって初期化します。このボタンをストーリーボードまたは XIB ファイルに追加するには、ビューを追加して、そのカスタムクラスをGIDSignInButton
に設定します。- 省略可: このボタンをカスタマイズする方法は次のとおりです。
Swift
- ビュー コントローラで、ログインボタンをプロパティとして宣言します。
@IBOutlet weak var signInButton: GIDSignInButton!
- 宣言した
signInButton
プロパティにボタンを接続します。 - GIDSignInButton オブジェクトのプロパティを設定してボタンをカスタマイズします。
Objective-C
- ビュー コントローラのヘッダー ファイルで、ログインボタンをプロパティとして宣言します。
@property(weak, nonatomic) IBOutlet GIDSignInButton *signInButton;
- 宣言した
signInButton
プロパティにボタンを接続します。 - GIDSignInButton オブジェクトのプロパティを設定してボタンをカスタマイズします。
- ビュー コントローラで、ログインボタンをプロパティとして宣言します。
3. Firebase で認証する
最後に、前の手順で作成した認証情報を使用して Firebase ログイン プロセスを完了します。
Swift
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 // ... }
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 プロジェクトの一部として保存され、ユーザーのログイン方法にかかわらず、プロジェクトのすべてのアプリでユーザーを識別するために使用できます。
-
アプリでは、
FIRUser
オブジェクトからユーザーの基本的なプロフィール情報を取得できます。ユーザーを管理するをご覧ください。 Firebase Realtime Database と Cloud Storage のセキュリティ ルールでは、ログイン済みユーザーの一意のユーザー ID を
auth
変数から取得し、それを使用して、ユーザーがアクセスできるデータを管理できます。
既存のユーザー アカウントに認証プロバイダの認証情報をリンクすることで、ユーザーは複数の認証プロバイダを使用してアプリにログインできるようになります。
ユーザーのログアウトを行うには、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; }
さまざまな認証エラーに対応できるようにエラー処理コードを追加することもできます。エラーの処理をご覧ください。