アプリを Firebase に接続する
まだ行っていない場合は、 Firebase を Android プロジェクトに追加します。
アプリに Firebase Authentication を追加する
モジュール (アプリ レベル) の 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 コンソールで有効にする必要があります。 [Firebase 認証] セクションの [サインイン方法] ページに移動して、メール/パスワードによるサインインと、アプリに必要なその他の ID プロバイダーを有効にします。
(省略可)Firebase Local Emulator Suite でプロトタイプを作成してテストする
アプリがユーザーを認証する方法について説明する前に、認証機能のプロトタイプとテストに使用できる一連のツール、Firebase Local Emulator Suite を紹介しましょう。認証技術とプロバイダーを決定している場合、Authentication と Firebase セキュリティ ルールを使用してパブリック データとプライベート データでさまざまなデータ モデルを試している場合、またはサインイン UI デザインのプロトタイプを作成している場合、ライブ サービスをデプロイせずにローカルで作業できることは素晴らしいアイデアです。 .
認証エミュレーターはローカル エミュレーター スイートの一部であり、アプリがエミュレートされたデータベースのコンテンツと構成、および必要に応じてエミュレートされたプロジェクト リソース (関数、他のデータベース、およびセキュリティ ルール) とやり取りできるようにします。
認証エミュレーターを使用するには、いくつかの手順が必要です。
- アプリのテスト構成にコード行を追加して、エミュレーターに接続します。
- ローカル プロジェクト ディレクトリのルートから、
firebase emulators:start
を実行します。 - インタラクティブなプロトタイピングにはローカル エミュレーター スイート UI を使用し、非インタラクティブなテストには認証エミュレーター REST API を使用します。
詳細なガイドは、アプリを認証エミュレーターに接続するで入手できます。詳細については、 Local Emulator Suiteの概要を参照してください。
それでは、ユーザーを認証する方法を続けましょう。
現在の認証状態を確認する
FirebaseAuth
のインスタンスを宣言します。Kotlin+KTX
private lateinit var auth: FirebaseAuth
Java
private FirebaseAuth mAuth;
onCreate()
メソッドで、FirebaseAuth
インスタンスを初期化します。Kotlin+KTX
// Initialize Firebase Auth auth = Firebase.auth
Java
// 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
メソッドを使用して新しいユーザーを作成する新しいcreateAccount
メソッドを作成します。
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); } } });
電子メールとパスワードで新しいユーザーを登録するフォームを追加し、送信時にこの新しいメソッドを呼び出します。クイックスタート サンプルで例を確認できます。
既存のユーザーにサインインする
電子メール アドレスとパスワードをsignInWithEmailAndPassword
signIn
を使用してユーザーをサインインさせる新しいサインイン メソッドを作成します。
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 および認証サービスの追加に関するガイドを参照してください。