アプリを Firebase に接続する
まだ Firebase を Android プロジェクトに追加していない場合は追加します。
アプリに Firebase Authentication を追加する
Firebase Android BoM を使用して、モジュール(アプリレベル)の Gradle ファイル(通常はapp/build.gradle
)で Firebase Authentication Android ライブラリの依存関係を宣言します。
Java
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:26.2.0') // Declare 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 { // Declare 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:20.0.1' }
Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:26.2.0') // Declare 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 { // Declare 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:20.0.1' }
認証プロバイダを使用するには、Firebase コンソールで認証プロバイダを有効にする必要があります。[Authentication] セクションの [ログイン方法] ページに移動して、[メール / パスワード] のほか、アプリに必要な ID プロバイダを有効にします。
現在の認証状態を確認する
FirebaseAuth
インスタンスを宣言します。Java
private FirebaseAuth mAuth;
Kotlin+KTX
private lateinit var auth: FirebaseAuth
onCreate()
メソッドで、FirebaseAuth
インスタンスを初期化します。Java
// Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
Kotlin+KTX
// Initialize Firebase Auth auth = Firebase.auth
アクティビティを初期化するときに、ユーザーが現在ログインしているかどうかを確認します。
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); }
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) }
新しいユーザーを登録する
新しい createAccount
メソッドを作成します。このメソッドでは、メールアドレスとパスワードを受け取ってその内容を検証し、createUserWithEmailAndPassword
メソッドを使用して新しいユーザーを作成します。
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); } // ... } });
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) } // ... }
メールアドレスとパスワードで新しいユーザーを登録するフォームを追加し、送信時にこの新しいメソッドを呼び出します。クイックスタート サンプルで例をご確認いただけます。
既存のユーザーをログインさせる
メールアドレスとパスワードを受け取る新しい signIn
メソッドを作成して検証し、signInWithEmailAndPassword
メソッドでユーザーをログインさせます。
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); // ... } // ... } });
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) // ... } // ... }
メールアドレスとパスワードでユーザーをログインさせるフォームを追加し、送信時にこの新しいメソッドを呼び出します。クイックスタート サンプルで例をご確認いただけます。
ユーザー情報にアクセスする
ユーザーが正常にログインした場合、getCurrentUser
メソッドでいつでもアカウント データを取得できます。
Java
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { // Name, email address, and profile photo Url String name = user.getDisplayName(); String email = user.getEmail(); Uri photoUrl = user.getPhotoUrl(); // Check if user's email is verified boolean emailVerified = user.isEmailVerified(); // The user's ID, unique to the Firebase project. Do NOT use this value to // authenticate with your backend server, if you have one. Use // FirebaseUser.getIdToken() instead. String uid = user.getUid(); }
Kotlin+KTX
val user = Firebase.auth.currentUser user?.let { // Name, email address, and profile photo Url val name = user.displayName val email = user.email val photoUrl = user.photoUrl // Check if user's email is verified val emailVerified = user.isEmailVerified // The user's ID, unique to the Firebase project. Do NOT use this value to // authenticate with your backend server, if you have one. Use // FirebaseUser.getToken() instead. val uid = user.uid }
次のステップ
他の ID や認証サービスの追加については、以下のガイドをご覧ください。