アプリに Facebook ログインを統合することで、ユーザーが Facebook アカウントを使用して Firebase で認証できるようにすることができます。
あなたが始める前に
まだ行っていない場合は、 Firebase を Android プロジェクトに追加します。
- Facebook for Developersサイトで、アプリのアプリ IDとアプリ シークレットを取得します。
- Facebook ログインを有効にする:
- Firebase コンソールで、 Authセクションを開きます。
- [サインイン方法] タブで、 Facebookサインイン方法を有効にし、Facebook から取得したアプリ IDとアプリ シークレットを指定します。
- 次に、 OAuth リダイレクト URI (例:
my-app-12345.firebaseapp.com/__/auth/handler
) が、製品のFacebook for Developersサイトの Facebook アプリの設定ページにOAuth リダイレクト URIの 1 つとしてリストされていることを確認します。設定 > Facebook ログイン設定。
モジュール (アプリ レベル) の Gradle ファイル(通常は
<project>/<app-module>/build.gradle
) で、Firebase Authentication Android ライブラリの依存関係を追加します。ライブラリのバージョン管理には、 Firebase Android BoMを使用することをお勧めします。Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.0') // Add the dependency for the Firebase Authentication library // When using the BoM, you don't specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-auth-ktx' }
Firebase Android BoMを使用すると、アプリは常に互換性のあるバージョンの Firebase Android ライブラリを使用します。
(代替) BoM を使用せずに Firebase ライブラリの依存関係を追加する
Firebase BoM を使用しないことを選択した場合は、依存関係の行で各 Firebase ライブラリ バージョンを指定する必要があります。
アプリで複数のFirebase ライブラリを使用する場合は、BoM を使用してライブラリ バージョンを管理することを強くお勧めします。これにより、すべてのバージョンに互換性が確保されます。
dependencies { // Add the dependency for the Firebase Authentication library // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-auth-ktx:21.1.0' }
Java
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.0') // Add the dependency for the Firebase Authentication library // When using the BoM, you don't specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-auth' }
Firebase Android BoMを使用すると、アプリは常に互換性のあるバージョンの Firebase Android ライブラリを使用します。
(代替) BoM を使用せずに Firebase ライブラリの依存関係を追加する
Firebase BoM を使用しないことを選択した場合は、依存関係の行で各 Firebase ライブラリ バージョンを指定する必要があります。
アプリで複数のFirebase ライブラリを使用する場合は、BoM を使用してライブラリ バージョンを管理することを強くお勧めします。これにより、すべてのバージョンに互換性が確保されます。
dependencies { // Add the dependency for the Firebase Authentication library // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-auth:21.1.0' }
Firebase で認証する
- 開発者のドキュメントに従って、Facebook ログインをアプリに統合します。
LoginButton
またはLoginManager
オブジェクトを構成するときは、public_profile
およびemail
権限を要求します。LoginButton
を使用して Facebook ログインを統合した場合、サインイン アクティビティには次のようなコードが含まれます。Kotlin+KTX
// Initialize Facebook Login button callbackManager = CallbackManager.Factory.create() buttonFacebookLogin.setReadPermissions("email", "public_profile") buttonFacebookLogin.registerCallback(callbackManager, object : FacebookCallback<LoginResult> { override fun onSuccess(loginResult: LoginResult) { Log.d(TAG, "facebook:onSuccess:$loginResult") handleFacebookAccessToken(loginResult.accessToken) } override fun onCancel() { Log.d(TAG, "facebook:onCancel") } override fun onError(error: FacebookException) { Log.d(TAG, "facebook:onError", error) } }) // ... override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) // Pass the activity result back to the Facebook SDK callbackManager.onActivityResult(requestCode, resultCode, data) }
Java
// Initialize Facebook Login button mCallbackManager = CallbackManager.Factory.create(); LoginButton loginButton = findViewById(R.id.button_sign_in); loginButton.setReadPermissions("email", "public_profile"); loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { Log.d(TAG, "facebook:onSuccess:" + loginResult); handleFacebookAccessToken(loginResult.getAccessToken()); } @Override public void onCancel() { Log.d(TAG, "facebook:onCancel"); } @Override public void onError(FacebookException error) { Log.d(TAG, "facebook:onError", error); } }); // ... @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Pass the activity result back to the Facebook SDK mCallbackManager.onActivityResult(requestCode, resultCode, data); }
- サインイン アクティビティの
onCreate
メソッドで、FirebaseAuth
オブジェクトの共有インスタンスを取得します。Kotlin+KTX
private lateinit var auth: FirebaseAuth // ... // Initialize Firebase Auth auth = Firebase.auth
Java
private FirebaseAuth mAuth; // ... // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
- アクティビティを初期化するときに、ユーザーが現在サインインしているかどうかを確認します。
Kotlin+KTX
public override fun onStart() { super.onStart() // Check if user is signed in (non-null) and update UI accordingly. val currentUser = auth.currentUser updateUI(currentUser) }
Java
@Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); updateUI(currentUser); }
- ユーザーが正常にサインインしたら、
LoginButton
のonSuccess
コールバック メソッドで、サインインしているユーザーのアクセス トークンを取得し、それを Firebase 資格情報と交換し、Firebase 資格情報を使用して Firebase で認証します。Kotlin+KTX
private fun handleFacebookAccessToken(token: AccessToken) { Log.d(TAG, "handleFacebookAccessToken:$token") val credential = FacebookAuthProvider.getCredential(token.token) auth.signInWithCredential(credential) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithCredential:success") val user = auth.currentUser updateUI(user) } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithCredential:failure", task.exception) Toast.makeText(baseContext, "Authentication failed.", Toast.LENGTH_SHORT).show() updateUI(null) } } }
Java
private void handleFacebookAccessToken(AccessToken token) { Log.d(TAG, "handleFacebookAccessToken:" + token); AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken()); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithCredential:success"); FirebaseUser user = mAuth.getCurrentUser(); updateUI(user); } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithCredential:failure", task.getException()); Toast.makeText(FacebookLoginActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); updateUI(null); } } }); }
signInWithCredential
の呼び出しが成功した場合は、getCurrentUser
メソッドを使用してユーザーのアカウント データを取得できます。
次のステップ
ユーザーが初めてサインインすると、新しいユーザー アカウントが作成され、サインインに使用したユーザーの資格情報 (ユーザー名とパスワード、電話番号、または認証プロバイダー情報) にリンクされます。この新しいアカウントは Firebase プロジェクトの一部として保存され、ユーザーのサインイン方法に関係なく、プロジェクト内のすべてのアプリでユーザーを識別するために使用できます。
アプリでは、ユーザーの基本的なプロフィール情報を
FirebaseUser
オブジェクトから取得できます。ユーザーの管理を参照してください。Firebase Realtime Database と Cloud Storageセキュリティ ルールでは、サインインしているユーザーの一意のユーザー ID を
auth
変数から取得し、それを使用してユーザーがアクセスできるデータを制御できます。
認証プロバイダーの資格情報を既存のユーザー アカウントにリンクすることで、ユーザーが複数の認証プロバイダーを使用してアプリにサインインできるようにすることができます。
ユーザーをサインアウトするには、 signOut
を呼び出します。
Kotlin+KTX
Firebase.auth.signOut()
Java
FirebaseAuth.getInstance().signOut();