Android で Firebase Authentication を使ってみる

アプリを Firebase に接続する

まだ Firebase を Android プロジェクトに追加していない場合は追加します。

アプリに Firebase Authentication を追加する

モジュール(アプリレベル)の Gradle ファイル(通常は <project>/<app-module>/build.gradle.kts または <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:32.3.1"))

    // 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 部品構成表を使用すると、アプリは常に互換性のあるバージョンの 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:22.1.2")
}

Java

dependencies {
    // Import the BoM for the Firebase platform
    implementation(platform("com.google.firebase:firebase-bom:32.3.1"))

    // 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 部品構成表を使用すると、アプリは常に互換性のあるバージョンの 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:22.1.2")
}

認証プロバイダを使用するには、Firebase コンソールで認証プロバイダを有効にする必要があります。[Authentication] セクションの [Sign-in method] ページに移動して、[メール / パスワード] のほか、アプリに必要な ID プロバイダを有効にします。

(省略可)Firebase Local Emulator Suite でプロトタイピングおよびテストを行う

アプリによるユーザーの認証方法について見ていく前に、Authentication 機能のプロトタイピングとテストに使用できるツール、Firebase Local Emulator Suite をご紹介します。認証手法やプロバイダを検討している場合や、Authentication と Firebase セキュリティ ルールを使用して公開および非公開のデータで各種データモデルを試している場合、さらにログイン時の UI デザインのプロトタイプを作成している場合などは、ライブサービスをデプロイせずにローカルで作業できると便利です。

Local Emulator Suite の一部である Authentication エミュレータを使用すると、アプリはエミュレートされたデータベースのコンテンツと構成のほか、プロジェクト リソース(関数、他のデータベース、セキュリティ ルール)ともやり取りできます。

いくつかの手順を実施するだけで、Authentication エミュレータを使用できます。

  1. アプリのテスト構成にコード行を追加して、エミュレータに接続します。
  2. ローカル プロジェクトのディレクトリのルートから、firebase emulators:start を実行します。
  3. 対話型のプロトタイピングには Local Emulator Suite UI を使用し、非対話型のテストには Authentication エミュレータ REST API を使用します。

詳細な手順については、アプリを Authentication エミュレータに接続するをご覧ください。また、Local Emulator Suite の概要もご覧ください。

次に、ユーザーの認証方法を見てみましょう。

現在の認証状態を確認する

  1. FirebaseAuth インスタンスを宣言します。

    Kotlin+KTX

    private lateinit var auth: FirebaseAuth

    Java

    private FirebaseAuth mAuth;
  2. onCreate() メソッドで、FirebaseAuth インスタンスを初期化します。

    Kotlin+KTX

    // Initialize Firebase Auth
    auth = Firebase.auth

    Java

    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();
  3. アクティビティを初期化するときに、ユーザーが現在ログインしているかどうかを確認します。

    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();
        }
    }

新しいユーザーを登録する

新しい createAccount メソッドを作成します。このメソッドでは、メールアドレスとパスワードを受け取ってその内容を検証し、createUserWithEmailAndPassword メソッドを使用して新しいユーザーを作成します。

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);
                }
            }
        });

メールアドレスとパスワードで新しいユーザーを登録するフォームを追加し、送信時にこの新しいメソッドを呼び出します。クイックスタート サンプルで例をご確認いただけます。

既存のユーザーをログインさせる

メールアドレスとパスワードを受け取ってその内容を検証する新しい signIn メソッドを作成し、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);
                }
            }
        });

メールアドレスとパスワードでユーザーをログインさせるフォームを追加し、送信時にこの新しいメソッドを呼び出します。クイックスタート サンプルで例をご確認いただけます。

ユーザー情報にアクセスする

ユーザーが正常にログインした場合、getCurrentUser メソッドでいつでもアカウント データを取得できます。

Kotlin+KTX

val user = Firebase.auth.currentUser
user?.let {
    // Name, email address, and profile photo Url
    val name = it.displayName
    val email = it.email
    val photoUrl = it.photoUrl

    // Check if user's email is verified
    val emailVerified = it.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.
    val uid = it.uid
}

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();
}

次のステップ

他の ID や認証サービスの追加については、以下のガイドをご覧ください。