Firebase Authentication with Identity Platform'a yükselttiyseniz Android uygulamanıza SMS çok faktörlü kimlik doğrulaması ekleyebilirsiniz.
Çok faktörlü kimlik doğrulama, uygulamanızın güvenliğini artırır. Saldırganlar genellikle parolaları ve sosyal hesapları ele geçirse de, bir metin mesajını ele geçirmek daha zordur.
Sen başlamadan önce
Çok faktörlü kimlik doğrulamayı destekleyen en az bir sağlayıcıyı etkinleştirin. Telefonla kimlik doğrulama, anonim kimlik doğrulama ve Apple Game Center dışında her sağlayıcı MFA'yı destekler.
Uygulamanızın kullanıcı e-postalarını doğruladığından emin olun. MFA, e-posta doğrulaması gerektirir. Bu, kötü niyetli aktörlerin sahip olmadıkları bir e-posta ile bir hizmete kaydolmalarını ve ardından ikinci bir faktör ekleyerek gerçek sahibi kilitlemelerini engeller.
Uygulamanızın SHA-1 karmasını Firebase Konsoluna kaydedin (değişiklikleriniz otomatik olarak Google Cloud Firebase'e taşınır).
Uygulamanızın SHA-1 karmasını almak için İstemcinizin kimliğini doğrulama bölümündeki adımları izleyin.
Firebase Konsolunu açın.
Proje Ayarları'na gidin.
Uygulamalarınız altında, Android simgesini tıklayın.
SHA-1 karmanızı eklemek için kılavuzlu adımları izleyin.
Çok faktörlü kimlik doğrulamayı etkinleştirme
Firebase konsolunun Kimlik Doğrulama > Oturum açma yöntemi sayfasını açın.
Gelişmiş bölümünde, SMS Çok Faktörlü Kimlik Doğrulamayı etkinleştirin.
Uygulamanızı test edeceğiniz telefon numaralarını da girmelisiniz. İsteğe bağlı olmakla birlikte, geliştirme sırasında kısıtlamayı önlemek için test telefon numaralarının kaydedilmesi şiddetle önerilir.
Uygulamanızın alan adını henüz yetkilendirmediyseniz, onu Firebase konsolunun Kimlik Doğrulama > Ayarlar sayfasındaki izin verilenler listesine ekleyin.
Bir kayıt modeli seçme
Uygulamanızın çok faktörlü kimlik doğrulaması gerektirip gerektirmediğini ve kullanıcılarınızı nasıl ve ne zaman kaydettireceğinizi seçebilirsiniz. Bazı yaygın desenler şunları içerir:
Kullanıcının ikinci faktörünü kaydın bir parçası olarak kaydedin. Uygulamanız tüm kullanıcılar için çok faktörlü kimlik doğrulama gerektiriyorsa bu yöntemi kullanın.
Kayıt sırasında ikinci bir faktörü kaydetmek için atlanabilir bir seçenek sunun. Çok faktörlü kimlik doğrulamayı teşvik etmek isteyen ancak gerektirmeyen uygulamalar bu yaklaşımı tercih edebilir.
Kaydolma ekranı yerine kullanıcının hesabından veya profil yönetimi sayfasından ikinci bir faktör ekleme olanağı sağlayın. Bu, kayıt işlemi sırasındaki sürtünmeyi en aza indirirken, güvenlik açısından hassas kullanıcılar için çok faktörlü kimlik doğrulamayı kullanıma sunmaya devam eder.
Kullanıcı, artırılmış güvenlik gereksinimlerine sahip özelliklere erişmek istediğinde, ikinci bir faktörün aşamalı olarak eklenmesini gerektir.
İkinci bir faktörün kaydedilmesi
Bir kullanıcı için yeni bir ikincil faktör kaydetmek için:
Kullanıcının kimliğini yeniden doğrulayın.
Kullanıcıdan telefon numarasını girmesini isteyin.
Kullanıcı için çok faktörlü bir oturum alın:
Kotlin+KTX
user.multiFactor.session.addOnCompleteListener { task -> if (task.isSuccessful) { val multiFactorSession: MultiFactorSession? = task.result } }
Java
user.getMultiFactor().getSession() .addOnCompleteListener( new OnCompleteListener<MultiFactorSession>() { @Override public void onComplete(@NonNull Task<MultiFactorSession> task) { if (task.isSuccessful()) { MultiFactorSession multiFactorSession = task.getResult(); } } });
Doğrulama sürecinde farklı olayları işlemek için bir
OnVerificationStateChangedCallbacks
nesnesi oluşturun:Kotlin+KTX
val callbacks = object : OnVerificationStateChangedCallbacks() { override fun onVerificationCompleted(credential: PhoneAuthCredential) { // This callback will be invoked in two situations: // 1) Instant verification. In some cases, the phone number can be // instantly verified without needing to send or enter a verification // code. You can disable this feature by calling // PhoneAuthOptions.builder#requireSmsValidation(true) when building // the options to pass to PhoneAuthProvider#verifyPhoneNumber(). // 2) Auto-retrieval. On some devices, Google Play services can // automatically detect the incoming verification SMS and perform // verification without user action. this@MainActivity.credential = credential } override fun onVerificationFailed(e: FirebaseException) { // This callback is invoked in response to invalid requests for // verification, like an incorrect phone number. if (e is FirebaseAuthInvalidCredentialsException) { // Invalid request // ... } else if (e is FirebaseTooManyRequestsException) { // The SMS quota for the project has been exceeded // ... } // Show a message and update the UI // ... } override fun onCodeSent( verificationId: String, forceResendingToken: ForceResendingToken ) { // The SMS verification code has been sent to the provided phone number. // We now need to ask the user to enter the code and then construct a // credential by combining the code with a verification ID. // Save the verification ID and resending token for later use. this@MainActivity.verificationId = verificationId this@MainActivity.forceResendingToken = forceResendingToken // ... } }
Java
OnVerificationStateChangedCallbacks callbacks = new OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(PhoneAuthCredential credential) { // This callback will be invoked in two situations: // 1) Instant verification. In some cases, the phone number can be // instantly verified without needing to send or enter a verification // code. You can disable this feature by calling // PhoneAuthOptions.builder#requireSmsValidation(true) when building // the options to pass to PhoneAuthProvider#verifyPhoneNumber(). // 2) Auto-retrieval. On some devices, Google Play services can // automatically detect the incoming verification SMS and perform // verification without user action. this.credential = credential; } @Override public void onVerificationFailed(FirebaseException e) { // This callback is invoked in response to invalid requests for // verification, like an incorrect phone number. if (e instanceof FirebaseAuthInvalidCredentialsException) { // Invalid request // ... } else if (e instanceof FirebaseTooManyRequestsException) { // The SMS quota for the project has been exceeded // ... } // Show a message and update the UI // ... } @Override public void onCodeSent( String verificationId, PhoneAuthProvider.ForceResendingToken token) { // The SMS verification code has been sent to the provided phone number. // We now need to ask the user to enter the code and then construct a // credential by combining the code with a verification ID. // Save the verification ID and resending token for later use. this.verificationId = verificationId; this.forceResendingToken = token; // ... } };
Kullanıcının telefon numarası, çok faktörlü oturum ve geri aramalarınızla bir
PhoneInfoOptions
nesnesi başlatın:Kotlin+KTX
val phoneAuthOptions = PhoneAuthOptions.newBuilder() .setPhoneNumber(phoneNumber) .setTimeout(30L, TimeUnit.SECONDS) .setMultiFactorSession(MultiFactorSession) .setCallbacks(callbacks) .build()
Java
PhoneAuthOptions phoneAuthOptions = PhoneAuthOptions.newBuilder() .setPhoneNumber(phoneNumber) .setTimeout(30L, TimeUnit.SECONDS) .setMultiFactorSession(multiFactorSession) .setCallbacks(callbacks) .build();
Varsayılan olarak, anında doğrulama etkindir. Devre dışı bırakmak için,
requireSmsValidation(true)
öğesine bir çağrı ekleyin.Kullanıcının telefonuna bir doğrulama mesajı gönderin:
Kotlin+KTX
PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions)
Java
PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions);
Zorunlu olmamakla birlikte, kullanıcıları bir SMS mesajı alacakları ve standart ücretlerin geçerli olduğu konusunda önceden bilgilendirmek en iyi uygulamadır.
SMS kodu gönderildiğinde, kullanıcıdan kodu doğrulamasını isteyin:
Kotlin+KTX
// Ask user for the verification code. val credential = PhoneAuthProvider.getCredential(verificationId, verificationCode)
Java
// Ask user for the verification code. PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, verificationCode);
PhoneAuthCredential ile bir
MultiFactorAssertion
nesnesiPhoneAuthCredential
:Kotlin+KTX
val multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential)
Java
MultiFactorAssertion multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential);
Kayıt işlemini tamamlayın. İsteğe bağlı olarak, ikinci faktör için bir görünen ad belirleyebilirsiniz. Bu, telefon numarası kimlik doğrulama akışı sırasında maskelendiğinden (örneğin, +1******1234) birden çok saniye faktörüne sahip kullanıcılar için kullanışlıdır.
Kotlin+KTX
// Complete enrollment. This will update the underlying tokens // and trigger ID token change listener. FirebaseAuth.getInstance() .currentUser ?.multiFactor ?.enroll(multiFactorAssertion, "My personal phone number") ?.addOnCompleteListener { // ... }
Java
// Complete enrollment. This will update the underlying tokens // and trigger ID token change listener. FirebaseAuth.getInstance() .getCurrentUser() .getMultiFactor() .enroll(multiFactorAssertion, "My personal phone number") .addOnCompleteListener( new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { // ... } });
Aşağıdaki kod, ikinci bir faktörü kaydetmenin tam bir örneğini göstermektedir:
Kotlin+KTX
val multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential)
user.multiFactor.session
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val multiFactorSession = task.result
val phoneAuthOptions = PhoneAuthOptions.newBuilder()
.setPhoneNumber(phoneNumber)
.setTimeout(30L, TimeUnit.SECONDS)
.setMultiFactorSession(multiFactorSession)
.setCallbacks(callbacks)
.build()
// Send SMS verification code.
PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions)
}
}
// Ask user for the verification code.
val credential = PhoneAuthProvider.getCredential(verificationId, verificationCode)
val multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential)
// Complete enrollment.
FirebaseAuth.getInstance()
.currentUser
?.multiFactor
?.enroll(multiFactorAssertion, "My personal phone number")
?.addOnCompleteListener {
// ...
}
Java
MultiFactorAssertion multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential);
user.getMultiFactor().getSession()
.addOnCompleteListener(
new OnCompleteListener<MultiFactorSession>() {
@Override
public void onComplete(@NonNull Task<MultiFactorSession> task) {
if (task.isSuccessful()) {
MultiFactorSession multiFactorSession = task.getResult();
PhoneAuthOptions phoneAuthOptions =
PhoneAuthOptions.newBuilder()
.setPhoneNumber(phoneNumber)
.setTimeout(30L, TimeUnit.SECONDS)
.setMultiFactorSession(multiFactorSession)
.setCallbacks(callbacks)
.build();
// Send SMS verification code.
PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions);
}
}
});
// Ask user for the verification code.
PhoneAuthCredential credential =
PhoneAuthProvider.getCredential(verificationId, verificationCode);
MultiFactorAssertion multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential);
// Complete enrollment.
FirebaseAuth.getInstance()
.getCurrentUser()
.getMultiFactor()
.enroll(multiFactorAssertion, "My personal phone number")
.addOnCompleteListener(
new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
// ...
}
});
Tebrikler! Bir kullanıcı için ikinci bir kimlik doğrulama faktörünü başarıyla kaydettiniz.
Kullanıcıları ikinci bir faktörle oturum açma
İki faktörlü SMS doğrulaması ile bir kullanıcıda oturum açmak için:
Kullanıcının ilk faktörüyle oturum açın, ardından
FirebaseAuthMultiFactorException
istisnasını yakalayın. Bu hata, kullanıcının kayıtlı ikinci faktörlerini elde etmek için kullanabileceğiniz bir çözümleyici içerir. Ayrıca, kullanıcının ilk faktörüyle başarılı bir şekilde kimliğinin doğrulandığını kanıtlayan temel bir oturum içerir.Örneğin, kullanıcının ilk faktörü bir e-posta ve şifre ise:
Kotlin+KTX
FirebaseAuth.getInstance() .signInWithEmailAndPassword(email, password) .addOnCompleteListener( OnCompleteListener { task -> if (task.isSuccessful) { // User is not enrolled with a second factor and is successfully // signed in. // ... return@OnCompleteListener } if (task.exception is FirebaseAuthMultiFactorException) { // The user is a multi-factor user. Second factor challenge is // required. val multiFactorResolver = (task.exception as FirebaseAuthMultiFactorException).resolver // ... } else { // Handle other errors, such as wrong password. } })
Java
FirebaseAuth.getInstance() .signInWithEmailAndPassword(email, password) .addOnCompleteListener( new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // User is not enrolled with a second factor and is successfully // signed in. // ... return; } if (task.getException() instanceof FirebaseAuthMultiFactorException) { // The user is a multi-factor user. Second factor challenge is // required. MultiFactorResolver multiFactorResolver = task.getException().getResolver(); // ... } else { // Handle other errors such as wrong password. } } });
Kullanıcının ilk faktörü OAuth gibi federe bir sağlayıcıysa,
startActivityForSignInWithProvider()
çağrıldıktan sonra hatayı yakalayın.Kullanıcının kayıtlı birden fazla ikincil faktörü varsa, hangisini kullanacaklarını sorun:
Kotlin+KTX
// Ask user which second factor to use. // You can get the list of enrolled second factors using // multiFactorResolver.hints // Check the selected factor: if (multiFactorResolver.hints[selectedIndex].factorId === PhoneMultiFactorGenerator.FACTOR_ID ) { // User selected a phone second factor. val selectedHint = multiFactorResolver.hints[selectedIndex] as PhoneMultiFactorInfo } else { // Unsupported second factor. // Note that only phone second factors are currently supported. }
Java
// Ask user which second factor to use. // You can get the masked phone number using // resolver.getHints().get(selectedIndex).getPhoneNumber() // You can get the display name using // resolver.getHints().get(selectedIndex).getDisplayName() if (resolver.getHints().get(selectedIndex).getFactorId() == PhoneMultiFactorGenerator.FACTOR_ID) { // User selected a phone second factor. MultiFactorInfo selectedHint = multiFactorResolver.getHints().get(selectedIndex); } else { // Unsupported second factor. // Note that only phone second factors are currently supported. }
İpucu ve çok faktörlü oturumla bir
PhoneAuthOptions
nesnesini başlatın. Bu değerler,FirebaseAuthMultiFactorException
eklenen çözümleyicide bulunur.Kotlin+KTX
val phoneAuthOptions = PhoneAuthOptions.newBuilder() .setMultiFactorHint(selectedHint) .setTimeout(30L, TimeUnit.SECONDS) .setMultiFactorSession(multiFactorResolver.session) .setCallbacks(callbacks) // Optionally disable instant verification. // .requireSmsValidation(true) .build()
Java
PhoneAuthOptions phoneAuthOptions = PhoneAuthOptions.newBuilder() .setMultiFactorHint(selectedHint) .setTimeout(30L, TimeUnit.SECONDS) .setMultiFactorSession(multiFactorResolver.getSession()) .setCallbacks(callbacks) // Optionally disable instant verification. // .requireSmsValidation(true) .build();
Kullanıcının telefonuna bir doğrulama mesajı gönderin:
Kotlin+KTX
// Send SMS verification code PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions)
Java
// Send SMS verification code PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions);
SMS kodu gönderildiğinde, kullanıcıdan kodu doğrulamasını isteyin:
Kotlin+KTX
// Ask user for the verification code. Then, pass it to getCredential: val credential = PhoneAuthProvider.getCredential(verificationId, verificationCode)
Java
// Ask user for the verification code. Then, pass it to getCredential: PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, verificationCode);
PhoneAuthCredential ile bir
MultiFactorAssertion
nesnesiPhoneAuthCredential
:Kotlin+KTX
val multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential)
Java
MultiFactorAssertion multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential);
İkincil kimlik doğrulamayı tamamlamak için
resolver.resolveSignIn()
'i arayın. Ardından, standart sağlayıcıya özel verileri ve kimlik doğrulama bilgilerini içeren orijinal oturum açma sonucuna erişebilirsiniz:Kotlin+KTX
multiFactorResolver .resolveSignIn(multiFactorAssertion) .addOnCompleteListener { task -> if (task.isSuccessful) { val authResult = task.result // AuthResult will also contain the user, additionalUserInfo, // and an optional credential (null for email/password) // associated with the first factor sign-in. // For example, if the user signed in with Google as a first // factor, authResult.getAdditionalUserInfo() will contain data // related to Google provider that the user signed in with; // authResult.getCredential() will contain the Google OAuth // credential; // authResult.getCredential().getAccessToken() will contain the // Google OAuth access token; // authResult.getCredential().getIdToken() contains the Google // OAuth ID token. } }
Java
multiFactorResolver .resolveSignIn(multiFactorAssertion) .addOnCompleteListener( new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { AuthResult authResult = task.getResult(); // AuthResult will also contain the user, additionalUserInfo, // and an optional credential (null for email/password) // associated with the first factor sign-in. // For example, if the user signed in with Google as a first // factor, authResult.getAdditionalUserInfo() will contain data // related to Google provider that the user signed in with. // authResult.getCredential() will contain the Google OAuth // credential. // authResult.getCredential().getAccessToken() will contain the // Google OAuth access token. // authResult.getCredential().getIdToken() contains the Google // OAuth ID token. } } });
Aşağıdaki kod, çok faktörlü bir kullanıcıda oturum açmanın tam bir örneğini gösterir:
Kotlin+KTX
FirebaseAuth.getInstance()
.signInWithEmailAndPassword(email, password)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
// User is not enrolled with a second factor and is successfully
// signed in.
// ...
return@addOnCompleteListener
}
if (task.exception is FirebaseAuthMultiFactorException) {
val multiFactorResolver =
(task.exception as FirebaseAuthMultiFactorException).resolver
// Ask user which second factor to use. Then, get
// the selected hint:
val selectedHint =
multiFactorResolver.hints[selectedIndex] as PhoneMultiFactorInfo
// Send the SMS verification code.
PhoneAuthProvider.verifyPhoneNumber(
PhoneAuthOptions.newBuilder()
.setActivity(this)
.setMultiFactorSession(multiFactorResolver.session)
.setMultiFactorHint(selectedHint)
.setCallbacks(generateCallbacks())
.setTimeout(30L, TimeUnit.SECONDS)
.build()
)
// Ask user for the SMS verification code, then use it to get
// a PhoneAuthCredential:
val credential =
PhoneAuthProvider.getCredential(verificationId, verificationCode)
// Initialize a MultiFactorAssertion object with the
// PhoneAuthCredential.
val multiFactorAssertion: MultiFactorAssertion =
PhoneMultiFactorGenerator.getAssertion(credential)
// Complete sign-in.
multiFactorResolver
.resolveSignIn(multiFactorAssertion)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
// User successfully signed in with the
// second factor phone number.
}
// ...
}
} else {
// Handle other errors such as wrong password.
}
}
Java
FirebaseAuth.getInstance()
.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(
new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// User is not enrolled with a second factor and is successfully
// signed in.
// ...
return;
}
if (task.getException() instanceof FirebaseAuthMultiFactorException) {
FirebaseAuthMultiFactorException e =
(FirebaseAuthMultiFactorException) task.getException();
MultiFactorResolver multiFactorResolver = e.getResolver();
// Ask user which second factor to use.
MultiFactorInfo selectedHint =
multiFactorResolver.getHints().get(selectedIndex);
// Send the SMS verification code.
PhoneAuthProvider.verifyPhoneNumber(
PhoneAuthOptions.newBuilder()
.setActivity(this)
.setMultiFactorSession(multiFactorResolver.getSession())
.setMultiFactorHint(selectedHint)
.setCallbacks(generateCallbacks())
.setTimeout(30L, TimeUnit.SECONDS)
.build());
// Ask user for the SMS verification code.
PhoneAuthCredential credential =
PhoneAuthProvider.getCredential(verificationId, verificationCode);
// Initialize a MultiFactorAssertion object with the
// PhoneAuthCredential.
MultiFactorAssertion multiFactorAssertion =
PhoneMultiFactorGenerator.getAssertion(credential);
// Complete sign-in.
multiFactorResolver
.resolveSignIn(multiFactorAssertion)
.addOnCompleteListener(
new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// User successfully signed in with the
// second factor phone number.
}
// ...
}
});
} else {
// Handle other errors such as wrong password.
}
}
});
Tebrikler! Çok faktörlü kimlik doğrulama kullanarak bir kullanıcıda başarıyla oturum açtınız.
Sıradaki ne
- Admin SDK ile çok faktörlü kullanıcıları programlı bir şekilde yönetin .