Identity Platform ile Firebase Authentication'a yükselttiyseniz Android uygulamanıza SMS ile çok öğeli kimlik doğrulamasını ekleyebilirsiniz.
Çok öğeli kimlik doğrulaması, uygulamanızın güvenliğini artırır. Saldırganlar genellikle şifrelerin ve sosyal hesapların güvenliğini ihlal etse de kısa mesajları ele geçirmek daha zordur.
Başlamadan önce
Çok öğeli kimlik doğrulamasını destekleyen en az bir sağlayıcıyı etkinleştirin. Her sağlayıcı; telefon kimlik doğrulaması, anonim kimlik doğrulama ve Apple Game Center haricinde MFA'yı destekler.
Uygulamanızın kullanıcı e-postalarını doğruladığından emin olun. MFA için e-posta doğrulaması gerekir. Bu, kötü niyetli kişilerin sahip olmadıkları bir e-postayla bir hizmete kaydolup ikinci bir etmen ekleyerek gerçek sahibini kilitlemelerini önler.
Uygulamanızın SHA-1 karmasını Firebase Konsolu'na kaydedin (değişiklikleriniz otomatik olarak Google Cloud Firebase'e aktarılır).
Uygulamanızın SHA-1 karmasını almak için İstemcinizin kimliğini doğrulama bölümündeki adımları uygulayın.
Firebase Konsolu'nu açın.
Proje Ayarları'na gidin.
Uygulamalarınız bölümünde Android simgesini tıklayın.
SHA-1 karmanızı eklemek için açıklamalı adımları uygulayın.
Çok öğeli kimlik doğrulamasını etkinleştirme
Firebase konsolunun Kimlik doğrulama > Oturum açma yöntemi sayfasını açın.
Gelişmiş bölümünde, SMS Çok Öğeli Kimlik Doğrulaması'nı etkinleştirin.
Ayrıca uygulamanızı test edeceğiniz telefon numaralarını da girmeniz gerekir. İsteğe bağlı olsa da, geliştirme sırasında kısıtlamadan kaçınmak için test telefon numaralarının kaydedilmesi önemle tavsiye edilir.
Uygulamanızın alanını henüz yetkilendirmediyseniz Firebase konsolunun Kimlik Doğrulama > Ayarlar sayfasındaki izin verilenler listesine ekleyin.
Kayıt kalıbı seçme
Uygulamanızın çok öğeli kimlik doğrulaması gerektirip gerektirmediğini ve kullanıcılarınızı nasıl ve ne zaman kaydedeceğinizi seçebilirsiniz. Bazı yaygın kalıplar şunlardır:
Kullanıcının ikinci faktörünü kayıt işleminin bir parçası olarak kaydedin. Uygulamanız tüm kullanıcılar için çok öğeli kimlik doğrulaması gerektiriyorsa bu yöntemi kullanın.
Kayıt sırasında ikinci bir faktör kaydettirmek için atlanabilir bir seçenek sunun. Çok öğeli kimlik doğrulamasını teşvik etmek isteyen ancak gerektirmeyen uygulamalar bu yaklaşımı tercih edebilir.
Kayıt ekranı yerine, kullanıcının hesap veya profil yönetimi sayfasından ikinci bir faktör ekleme olanağı sunun. Bu sayede hem kayıt işlemi sırasında yaşanabilecek sorunları en aza indirir hem de güvenlik açısından hassas kullanıcılar için çok öğeli kimlik doğrulamasını kullanılabilir hâle getirirsiniz.
Kullanıcı daha yüksek güvenlik gereksinimleri olan özelliklere erişmek istediğinde ikinci bir faktörün aşamalı olarak eklenmesini zorunlu kılın.
İkinci faktör kaydettirme
Bir kullanıcı için yeni bir ikincil faktör kaydettirme:
Kullanıcının kimliğini yeniden doğrulayın.
Kullanıcıdan telefon numarasını girmesini isteyin.
Kullanıcı için çok öğeli oturum alma:
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ı etkinlikleri 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 öğeli oturum ve geri çağırmalarınızla bir
PhoneInfoOptions
nesnesini 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. Bunu devre dışı bırakmak için
requireSmsValidation(true)
numarasına 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ılara bir SMS mesajı alacaklarını ve standart ücretlerin geçerli olacağını önceden bildirmek en iyi uygulamadır.
SMS kodu gönderildikten sonra 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);
Bir
MultiFactorAssertion
nesnesiniPhoneAuthCredential
ile başlatın:Kotlin+KTX
val multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential)
Java
MultiFactorAssertion multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential);
Kaydı tamamlayın. İsteğe bağlı olarak, ikinci faktör için bir görünen ad belirtebilirsiniz. Telefon numarası kimlik doğrulama akışı sırasında maskelendiğinden bu yöntem, birden fazla ikinci faktöre sahip kullanıcılar için yararlıdır (örneğin, +1******1234).
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 kodda, ikinci bir faktör kaydetmeyle ilgili tam bir örnek gösterilmektedir:
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.
İkinci faktörle kullanıcıların oturum açmasını sağlama
İki faktörlü SMS doğrulamasıyla bir kullanıcının oturumunu açmak için:
Kullanıcının ilk faktörle oturum açmasını sağlayın, ardından
FirebaseAuthMultiFactorException
istisnasını yakalayın. Bu hata, kullanıcının kayıtlı ikinci faktörlerini öğrenmek için kullanabileceğiniz bir çözümleyici içerir. Ayrıca, kullanıcının ilk faktörle başarıyla doğrulandığını kanıtlayan temel bir oturum da içerir.Örneğin, kullanıcının ilk faktörü e-posta ve şifreyse:
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 birleşik bir sağlayıcıysa
startActivityForSignInWithProvider()
çağrısından sonra hatayı yakalayın.Birden fazla ikincil faktör kayıtlıysa hangisinin kullanılacağı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 if (multiFactorResolver.hints[selectedIndex].factorId === TotpMultiFactorGenerator.FACTOR_ID) { // User selected a TOTP second factor. } else { // Unsupported second factor. }
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() .equals( PhoneMultiFactorGenerator.FACTOR_ID ) ) { // User selected a phone second factor. MultiFactorInfo selectedHint = multiFactorResolver.getHints().get(selectedIndex); } else if ( resolver .getHints() .get(selectedIndex) .getFactorId() .equals(TotpMultiFactorGenerator.FACTOR_ID ) ) { // User selected a TOTP second factor. } else { // Unsupported second factor. }
İpucu ve çok öğeli oturumla bir
PhoneAuthOptions
nesnesini başlatın. Bu değerler,FirebaseAuthMultiFactorException
öğesine ekli çö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önderildikten sonra 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);
Bir
MultiFactorAssertion
nesnesiniPhoneAuthCredential
ile başlatın:Kotlin+KTX
val multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential)
Java
MultiFactorAssertion multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential);
İkincil kimlik doğrulamayı tamamlamak için
resolver.resolveSignIn()
numaralı telefonu arayın. Böylece, 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 kodda, çok öğeli bir kullanıcının oturum açmasıyla ilgili tam bir örnek gösterilmektedir:
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 öğeli kimlik doğrulamayı kullanarak bir kullanıcının oturumunu başarıyla açtınız.
Sırada ne var?
- Admin SDK ile çok öğeli kullanıcıları programatik olarak yönetin.