アプリを 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:30.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:21.0.6' }
Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:30.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:21.0.6' }
認証プロバイダを使用するには、Firebase コンソールで認証プロバイダを有効にする必要があります。[Authentication] セクションの [Sign-in method] ページに移動して、[メール / パスワード] のほか、アプリに必要な ID プロバイダを有効にします。
(省略可)Firebase Local Emulator Suite でプロトタイピングおよびテストを行う
アプリがユーザーをどのように認証するのかを説明する前に、Authentication 機能のプロトタイピングとテストに使用できるツール、Firebase Local Emulator Suite についてご紹介します。たとえば、認証手法やプロバイダを選択している。または、Authentication ルールと Firebase セキュリティ ルールを使用してパブリック データとプライベート データでさまざまなデータモデルを試している。または、ログイン UI デザインのプロトタイプを作成している場合、ライブサービスをデプロイせずにローカルで作業できるようにすることは、良い手段です。
Authentication エミュレータは Local Emulator Suite の一部であり、これを使用すると、アプリはエミュレートされたデータベースのコンテンツと構成のほか、エミュレートされたプロジェクト リソース(関数、他のデータベース、セキュリティ ルール)ともオプションでやり取りできます。
Authentication エミュレータを使用するには、いくつかの手順を実施するだけです。
- アプリのテスト構成にコード行を追加して、エミュレータに接続します。
- ローカル プロジェクトのディレクトリのルートから、
firebase emulators:start
を実行します。 - 対話型のプロトタイピングには Local Emulator Suite UI を使用し、非対話型のテストには Authentication エミュレータ REST API を使用します。
詳しくは、アプリを Authentication エミュレータに接続するをご覧ください。詳細については、Local Emulator Suite の概要をご覧ください。
次に、ユーザーの認証方法を見てみましょう。
現在の認証状態を確認する
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(); if(currentUser != null){ reload(); } }
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(); } }
新しいユーザーを登録する
新しい 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 や認証サービスの追加については、以下のガイドをご覧ください。