Firebase SDK を使用して汎用の OAuth ログインをアプリに統合し、エンドツーエンドのログインフローを実行することで、ユーザーが Firebase での認証に Twitter などの OAuth プロバイダを使用できるようになります。
始める前に
Swift Package Manager を使用して Firebase の依存関係をインストールし、管理します。
- Xcode でアプリのプロジェクトを開いたまま、[File] > [Add Packages] の順に移動します。
- プロンプトが表示されたら、Firebase Apple プラットフォーム SDK リポジトリを追加します。
- Firebase Authentication ライブラリを選択します。
- ターゲットのビルド設定の [Other Linker Flags] セクションに -ObjCフラグを追加します。
- 上記の作業が完了すると、Xcode は依存関係の解決とバックグラウンドでのダウンロードを自動的に開始します。
https://github.com/firebase/firebase-ios-sdk.git
Twitter アカウントを使用してユーザーをログインさせるには、まず Firebase プロジェクトのログイン プロバイダとして Twitter を有効にする必要があります。
- Podfileに次の Pod を含めます。- pod 'FirebaseAuth' 
- Firebase コンソールで [Auth] セクションを開きます。
- [Sign-in method] タブで、[Twitter] プロバイダを有効にします。
- そのプロバイダのデベロッパー コンソールで取得した API キーと API Secret をプロバイダ構成に追加します。
  - Twitter でデベロッパー アプリケーションとしてアプリを登録し、アプリの OAuth API キーと API Secret を取得します。
- Twitter アプリの構成にあるアプリ設定ページで、Firebase OAuth リダイレクト URI(my-app-12345.firebaseapp.com/__/auth/handlerなど)を認可コールバック URL として設定します。
 
- [保存] をクリックします。
Firebase SDK を使用したログインフローの処理
Firebase Apple プラットフォーム SDK でログインフローを処理する手順は次のとおりです。
- Xcode プロジェクトにカスタム URL スキームを追加します。 - プロジェクト構成を開きます(左側のツリービューでプロジェクト名をダブルクリックします)。[TARGETS] セクションでアプリを選択し、[Info] タブを開いて [URL Types] セクションを展開します。
- [+] ボタンをクリックし、エンコードされたアプリ ID を URL スキームとして追加します。エンコードされたアプリ ID は、Firebase コンソールの [全般設定] ページで、iOS アプリのセクションで確認できます。その他のフィールドは空白にしておきます。
    完了すると、構成は次のようになります(ただし、値はアプリケーションによって異なります)。   
 
- プロバイダ ID OAuthProvider を使用して、OAuthProvider のインスタンスを作成します。 - Swift- var provider = OAuthProvider(providerID: "twitter.com") - Objective-C- FIROAuthProvider *provider = [FIROAuthProvider providerWithProviderID:@"twitter.com"]; 
- 省略可: OAuth リクエストと一緒に送信したい追加のカスタム OAuth パラメータを指定します。 - Swift- provider.customParameters = [ "lang": "fr" ] - Objective-C- [provider setCustomParameters:@{@"lang": @"fr"}]; - Twitter がサポートするパラメータについては、Twitter の OAuth に関するドキュメントをご覧ください。 - setCustomParametersで Firebase の必須パラメータを渡すことはできません。該当するパラメータは、client_id、redirect_uri、response_type、scope、state です。
- 省略可: アプリがユーザーに reCAPTCHA を表示する際の - SFSafariViewControllerまたは- UIWebViewの提示方法をカスタマイズするには、- AuthUIDelegateプロトコルに従ったカスタムクラスを作成して、そのクラスを- credentialWithUIDelegateに渡します。
- OAuth プロバイダ オブジェクトを使用して Firebase での認証を行います。 - Swift- provider.getCredentialWith(nil) { credential, error in if error != nil { // Handle error. } if credential != nil { Auth.auth().signIn(with: credential) { authResult, error in if error != nil { // Handle error. } // User is signed in. // IdP data available in authResult.additionalUserInfo.profile. // Twitter OAuth access token can also be retrieved by: // (authResult.credential as? OAuthCredential)?.accessToken // Twitter OAuth ID token can be retrieved by calling: // (authResult.credential as? OAuthCredential)?.idToken // Twitter OAuth secret can be retrieved by calling: // (authResult.credential as? OAuthCredential)?.secret } } } - Objective-C- [provider getCredentialWithUIDelegate:nil completion:^(FIRAuthCredential *_Nullable credential, NSError *_Nullable error) { if (error) { // Handle error. } if (credential) { [[FIRAuth auth] signInWithCredential:credential completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) { if (error) { // Handle error. } // User is signed in. // IdP data available in authResult.additionalUserInfo.profile. // Twitter OAuth access token can also be retrieved by: // authResult.credential.accessToken // Twitter OAuth ID token can be retrieved by calling: // authResult.credential.idToken // Twitter OAuth secret can be retrieved by calling: // authResult.credential.secret }]; } }]; - OAuth アクセス トークンを使用して、Twitter API を呼び出せます。 - たとえば、基本的なプロフィール情報を取得するには、 - Authorizationヘッダーにアクセス トークンを渡して REST API を呼び出します。- https://api.twitter.com/labs/1/users?usernames=TwitterDev 
- 上記の例ではログインフローを中心に説明していますが、Twitter プロバイダを既存のユーザーにリンクすることもできます。たとえば、複数のプロバイダを同じユーザーにリンクして、どれでもログイン可能にすることができます。 - Swift- Auth().currentUser.link(withCredential: credential) { authResult, error in if error != nil { // Handle error. } // Twitter credential is linked to the current user. // IdP data available in authResult.additionalUserInfo.profile. // Twitter OAuth access token can also be retrieved by: // (authResult.credential as? OAuthCredential)?.accessToken // Twitter OAuth ID token can be retrieved by calling: // (authResult.credential as? OAuthCredential)?.idToken // Twitter OAuth secret can be retrieved by calling: // (authResult.credential as? OAuthCredential)?.secret } - Objective-C- [[FIRAuth auth].currentUser linkWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { if (error) { // Handle error. } // Twitter credential is linked to the current user. // IdP data available in authResult.additionalUserInfo.profile. // Twitter OAuth access token is can also be retrieved by: // ((FIROAuthCredential *)authResult.credential).accessToken // Twitter OAuth ID token can be retrieved by calling: // ((FIROAuthCredential *)authResult.credential).idToken // Twitter OAuth secret can be retrieved by calling: // ((FIROAuthCredential *)authResult.credential).secret }]; 
- 同じパターンを - reauthenticateWithCredentialでも使用できます。これは、ログインしてから短時間のうちに行うべき機密性の高い操作のために、最新の認証情報を取得するのに使われます。- Swift- Auth().currentUser.reauthenticateWithCredential(withCredential: credential) { authResult, error in if error != nil { // Handle error. } // User is re-authenticated with fresh tokens minted and // should be able to perform sensitive operations like account // deletion and email or password update. // IdP data available in result.additionalUserInfo.profile. // Additional OAuth access token is can also be retrieved by: // (authResult.credential as? OAuthCredential)?.accessToken // Twitter OAuth ID token can be retrieved by calling: // (authResult.credential as? OAuthCredential)?.idToken // Twitter OAuth secret can be retrieved by calling: // (authResult.credential as? OAuthCredential)?.secret } - Objective-C- [[FIRAuth auth].currentUser reauthenticateWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { if (error) { // Handle error. } // User is re-authenticated with fresh tokens minted and // should be able to perform sensitive operations like account // deletion and email or password update. // IdP data available in result.additionalUserInfo.profile. // Additional OAuth access token is can also be retrieved by: // ((FIROAuthCredential *)authResult.credential).accessToken // Twitter OAuth ID token can be retrieved by calling: // ((FIROAuthCredential *)authResult.credential).idToken // Twitter OAuth secret can be retrieved by calling: // ((FIROAuthCredential *)authResult.credential).secret }]; 
次のステップ
ユーザーが初めてログインすると、新しいユーザー アカウントが作成され、ユーザーがログイン時に使用した認証情報(ユーザー名とパスワード、電話番号、または認証プロバイダ情報)にアカウントがリンクされます。この新しいアカウントは Firebase プロジェクトの一部として保存され、ユーザーのログイン方法にかかわらず、プロジェクトのすべてのアプリでユーザーを識別するために使用できます。
- 
アプリでは、 Userオブジェクトからユーザーの基本的なプロフィール情報を取得できます。ユーザーを管理するをご覧ください。
- 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; }
さまざまな認証エラーに対応できるようにエラー処理コードを追加することもできます。エラーの処理をご覧ください。