Firebase SDK を使用して一般的な OAuth ログインをアプリに統合し、エンド ツー エンドのサインイン フローを実行することで、Twitter などの OAuth プロバイダーを使用してユーザーが Firebase で認証できるようにすることができます。
あなたが始める前に
Swift Package Manager を使用して、Firebase の依存関係をインストールおよび管理します。
- Xcode で、アプリ プロジェクトを開いた状態で、 File > Add Packagesに移動します。
- プロンプトが表示されたら、Firebase Apple プラットフォーム SDK リポジトリを追加します。
- Firebase Authentication ライブラリを選択します。
- 完了すると、Xcode はバックグラウンドで依存関係の解決とダウンロードを自動的に開始します。
https://github.com/firebase/firebase-ios-sdk
Twitter アカウントを使用してユーザーをサインインさせるには、最初に Twitter を Firebase プロジェクトのサインイン プロバイダとして有効にする必要があります。
Podfile
に次のポッドを含めます:pod 'FirebaseAuth'
- Firebase コンソールで、 Authセクションを開きます。
- [サインイン方法] タブで、 Twitterプロバイダーを有効にします。
- そのプロバイダーの開発者コンソールからAPI キーとAPI シークレットをプロバイダー構成に追加します。
- アプリを開発者アプリケーションとして Twitter に登録し、アプリの OAuth API キーとAPI シークレットを取得します。
- Firebase OAuth リダイレクト URI (例:
my-app-12345.firebaseapp.com/__/auth/handler
) が、 Twitter アプリの config のアプリの設定ページで認証コールバック URLとして設定されていることを確認してください。
- [保存]をクリックします。
Firebase SDK でログイン フローを処理する
Firebase Apple プラットフォーム SDK でサインイン フローを処理するには、次の手順に従います。
カスタム URL スキームを Xcode プロジェクトに追加します。
- プロジェクト構成を開きます。左側のツリー ビューでプロジェクト名をダブルクリックします。 [ターゲット] セクションからアプリを選択し、[情報] タブを選択して、[ URL の種類] セクションを展開します。
- [ + ] ボタンをクリックし、反転したクライアント ID の URL スキームを追加します。この値を見つけるには、
構成ファイルを開き、GoogleService-Info.plist REVERSED_CLIENT_ID
キーを探します。そのキーの値をコピーして、構成ページの [ URL スキーム]ボックスに貼り付けます。他のフィールドは空白のままにします。完了すると、構成は次のようになります (ただし、アプリケーション固有の値があります)。
プロバイダー ID twitter.comを使用してOAuthProviderのインスタンスを作成します。
迅速
var provider = OAuthProvider(providerID: "twitter.com")
Objective-C
FIROAuthProvider *provider = [FIROAuthProvider providerWithProviderID:@"twitter.com"];
オプション: OAuth 要求で送信する追加のカスタム OAuth パラメーターを指定します。
迅速
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 で認証します。
迅速
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を呼び出すことができます。
たとえば、基本的なプロファイル情報を取得するには、REST API を呼び出して、
Authorization
ヘッダーでアクセス トークンを渡します。https://api.twitter.com/labs/1/users?usernames=TwitterDev
上記の例はサインイン フローに焦点を当てていますが、Twitter プロバイダーを既存のユーザーにリンクすることもできます。たとえば、複数のプロバイダーを同じユーザーにリンクして、いずれかでサインインできるようにすることができます。
迅速
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
で使用できます。これを使用して、最近のログインが必要な機密操作の新しい資格情報を取得できます。迅速
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:
を呼び出します。
迅速
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; }
認証エラーの全範囲に対してエラー処理コードを追加することもできます。エラーの処理を参照してください。