Firebase 인증을 사용하여 사용자가 이메일 주소와 비밀번호로 Firebase에 인증하도록 하고, 앱의 비밀번호 기반 계정을 관리할 수 있습니다.
시작하기 전에
아직 추가하지 않았다면 Android 프로젝트에 Firebase를 추가합니다.
- 아직 Firebase 프로젝트에 앱을 연결하지 않았다면 Firebase Console에서 연결합니다.
- 다음과 같이 이메일 및 비밀번호 로그인 방법을 사용 설정합니다.
- Firebase Console에서 인증 섹션을 엽니다.
- 로그인 방법 탭에서 이메일/비밀번호 로그인 방법을 사용 설정하고 저장을 클릭합니다.
Firebase Android BoM을 사용하여 모듈(앱 수준) Gradle 파일(일반적으로
app/build.gradle
)에서 Firebase 인증 Android 라이브러리의 종속 항목을 선언합니다.자바
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' }
비밀번호 기반 계정 만들기
비밀번호가 있는 신규 사용자 계정을 만들려면 앱의 로그인 작업에서 다음 절차를 완료합니다.
- 다음과 같이 로그인 작업의
onCreate
메서드에서FirebaseAuth
객체의 공유 인스턴스를 가져옵니다.자바
private FirebaseAuth mAuth; // ... // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
Kotlin+KTX
private lateinit var auth: FirebaseAuth // ... // Initialize Firebase Auth auth = Firebase.auth
- 활동을 초기화할 때 사용자가 현재 로그인되어 있는지 확인합니다.
자바
@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) }
- 신규 사용자가 앱의 가입 양식을 사용해 가입하고 나면 필요에 따라 앱에서 신규 계정 유효성 검사 절차를 완료합니다. 검사 항목의 예로는 신규 계정의 비밀번호를 정확하게 입력했는지, 비밀번호가 복잡성 조건을 충족하는지 등이 있습니다.
- 다음과 같이 신규 사용자의 이메일 주소와 비밀번호를
createUserWithEmailAndPassword
에 전달하여 신규 계정을 생성합니다.자바
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) } // ... }
getCurrentUser
메서드로 사용자의 계정 데이터를 가져올 수 있습니다.
사용자 로그인에 이메일 주소와 비밀번호 사용
비밀번호로 사용자 로그인을 처리하는 절차는 신규 계정을 생성하는 절차와 비슷합니다. 앱의 로그인 작업에서 다음 절차를 따르세요.
- 다음과 같이 로그인 작업의
onCreate
메서드에서FirebaseAuth
객체의 공유 인스턴스를 가져옵니다.자바
private FirebaseAuth mAuth; // ... // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
Kotlin+KTX
private lateinit var auth: FirebaseAuth // ... // Initialize Firebase Auth auth = Firebase.auth
- 활동을 초기화할 때 사용자가 현재 로그인되어 있는지 확인합니다.
자바
@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) }
- 사용자가 앱에 로그인하면 다음과 같이 사용자의 이메일 주소와 비밀번호를
signInWithEmailAndPassword
에 전달합니다.자바
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) // ... } // ... }
FirebaseUser
를 사용하여 계속 진행할 수 있습니다.
다음 단계
사용자가 처음으로 로그인하면 신규 사용자 계정이 생성되고 사용자 인증 정보(사용자가 로그인할 때 사용한 사용자 이름과 비밀번호, 전화번호 또는 인증 제공업체 정보)에 연결됩니다. 이 신규 계정은 Firebase 프로젝트에 저장되며 사용자의 로그인 방법과 무관하게 프로젝트 내의 모든 앱에서 사용자 본인 확인에 사용할 수 있습니다.
-
앱의
FirebaseUser
객체에서 사용자의 기본 프로필 정보를 가져올 수 있습니다. 사용자 관리를 참조하세요. Firebase 실시간 데이터베이스와 Cloud Storage 보안 규칙의
auth
변수에서 로그인한 사용자의 고유 사용자 ID를 가져온 후 이 ID를 통해 사용자가 액세스할 수 있는 데이터를 관리할 수 있습니다.
인증 제공업체의 사용자 인증 정보를 기존 사용자 계정에 연결하면 사용자가 여러 인증 제공업체를 통해 앱에 로그인할 수 있습니다.
사용자를 로그아웃시키려면 signOut
을 호출합니다.
자바
FirebaseAuth.getInstance().signOut();
Kotlin+KTX
Firebase.auth.signOut()