Firebase Authentication を使用すると、ユーザーがメール アドレスとパスワードを使用して Firebase で認証できるようにし、アプリのパスワード ベースのアカウントを管理できます。
あなたが始める前に
まだ行っていない場合は、 Firebase を Android プロジェクトに追加します。
- アプリを Firebase プロジェクトにまだ接続していない場合は、 Firebase コンソールから接続します。
- メール/パスワードによるサインインを有効にする:
- Firebase コンソールで、 Authセクションを開きます。
- [サインイン方法] タブで、電子メール/パスワードによるサインイン方法を有効にして、[保存] をクリックします。
モジュール (アプリ レベル) の 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' }
パスワードベースのアカウントを作成する
パスワードを使用して新しいユーザー アカウントを作成するには、アプリのサインイン アクティビティで次の手順を実行します。
- サインアップ アクティビティの
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 if(currentUser != null){ reload(); } }
Java
@Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); if(currentUser != null){ reload(); } }
- 新しいユーザーがアプリのサインアップ フォームを使用してサインアップするときは、新しいアカウントのパスワードが正しく入力され、複雑さの要件を満たしていることを確認するなど、アプリで必要な新しいアカウントの検証手順を完了します。
- 新しいユーザーの電子メール アドレスとパスワードを
createUserWithEmailAndPassword
に渡して、新しいアカウントを作成します。If the new account was created, the user is also signed in. コールバックでは、Kotlin+KTX
auth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "createUserWithEmail:success") val user = auth.currentUser updateUI(user) } else { // If sign in fails, display a message to the user. Log.w(TAG, "createUserWithEmail:failure", task.exception) Toast.makeText(baseContext, "Authentication failed.", Toast.LENGTH_SHORT).show() updateUI(null) } }
Java
mAuth.createUserWithEmailAndPassword(email, password) .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, "createUserWithEmail:success"); FirebaseUser user = mAuth.getCurrentUser(); updateUI(user); } else { // If sign in fails, display a message to the user. Log.w(TAG, "createUserWithEmail:failure", task.getException()); Toast.makeText(EmailPasswordActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); updateUI(null); } } });
getCurrentUser
メソッドを使用してユーザーのアカウント データを取得できます。
メールアドレスとパスワードを使用してユーザーにサインインする
パスワードを使用してユーザーをサインインする手順は、新しいアカウントを作成する手順と似ています。アプリのサインイン アクティビティで、次の操作を行います。
- サインイン アクティビティの
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 if(currentUser != null){ reload(); } }
Java
@Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); if(currentUser != null){ reload(); } }
- ユーザーがアプリにサインインするときに、ユーザーのメール アドレスとパスワードを
signInWithEmailAndPassword
に渡します。サインインが成功した場合は、返されたKotlin+KTX
auth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithEmail:success") val user = auth.currentUser updateUI(user) } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithEmail:failure", task.exception) Toast.makeText(baseContext, "Authentication failed.", Toast.LENGTH_SHORT).show() updateUI(null) } }
Java
mAuth.signInWithEmailAndPassword(email, password) .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, "signInWithEmail:success"); FirebaseUser user = mAuth.getCurrentUser(); updateUI(user); } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithEmail:failure", task.getException()); Toast.makeText(EmailPasswordActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); updateUI(null); } } });
FirebaseUser
を使用して続行できます。
推奨: メール列挙保護を有効にする
メール アドレスをパラメータとして受け取る一部の Firebase Authentication メソッドでは、登録が必要なときにメール アドレスが登録されていない場合 (たとえば、メール アドレスとパスワードを使用してサインインする場合)、または未使用である必要があるときに登録された場合 (たとえば、ユーザーのメールアドレスを変更する場合)。これは、ユーザーに特定の救済策を提案するのに役立ちますが、悪意のあるアクターが悪用して、ユーザーが登録した電子メール アドレスを発見することもできます。
このリスクを軽減するには、Google Cloud のgcloud
ツールを使用して、プロジェクトのメール列挙保護を有効にすることをお勧めします。この機能を有効にすると、Firebase Authentication のエラー報告の動作が変わることに注意してください。アプリがより具体的なエラーに依存していないことを確認してください。
次のステップ
ユーザーが初めてサインインすると、新しいユーザー アカウントが作成され、サインインに使用したユーザーの資格情報 (ユーザー名とパスワード、電話番号、または認証プロバイダー情報) にリンクされます。この新しいアカウントは Firebase プロジェクトの一部として保存され、ユーザーのサインイン方法に関係なく、プロジェクト内のすべてのアプリでユーザーを識別するために使用できます。
アプリでは、ユーザーの基本的なプロフィール情報を
FirebaseUser
オブジェクトから取得できます。ユーザーの管理を参照してください。Firebase Realtime Database と Cloud Storageセキュリティ ルールでは、サインインしているユーザーの一意のユーザー ID を
auth
変数から取得し、それを使用してユーザーがアクセスできるデータを制御できます。
認証プロバイダーの資格情報を既存のユーザー アカウントにリンクすることで、ユーザーが複数の認証プロバイダーを使用してアプリにサインインできるようにすることができます。
ユーザーをサインアウトするには、 signOut
を呼び出します。
Kotlin+KTX
Firebase.auth.signOut()
Java
FirebaseAuth.getInstance().signOut();