Firebase Authentication with Identity Platform sürümüne yükselttiyseniz web uygulamanıza SMS ile çok faktörlü kimlik doğrulama ekleyebilirsiniz.
Çok öğeli kimlik doğrulama, uygulamanızın güvenliğini artırır. Saldırganlar genellikle güvenliği ihlal edilmiş şifreleri ve sosyal medya hesaplarını ele geçirse 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. Telefon kimlik doğrulaması, anonim kimlik doğrulaması ve Apple Game Center hariç tüm sağlayıcılar çok faktörlü kimlik doğrulamayı destekler.
SMS ile kimlik doğrulamayı kullanmayı planladığınız bölgeleri etkinleştirin. Authentication, projelerinizi varsayılan olarak daha güvenli bir durumda oluşturmanıza yardımcı olan, tamamen engelleyici bir SMS bölge politikası kullanır.
Uygulamanızın kullanıcı e-postalarını doğruladığından emin olun. Çok faktörlü kimlik doğrulama için e-posta doğrulaması gerekir. Bu sayede, kötü niyetli kişilerin sahip olmadıkları bir e-posta adresiyle hizmete kaydolmaları ve ardından ikinci faktör ekleyerek gerçek sahibini engellemeleri önlenir.
Çoklu kiracı özelliğini kullanma
Çok öğeli kimlik doğrulamasını çok kiracılı bir ortamda kullanmak üzere etkinleştiriyorsanız aşağıdaki adımları (bu belgedeki diğer talimatlara ek olarak) tamamladığınızdan emin olun:
Google Cloud Console'da, çalışmak istediğiniz kiracıyı seçin.
Kodunuzda,
AuthörneğindekitenantIdalanını kiracınızın kimliğine ayarlayın. Örneğin:Web
import { getAuth } from "firebase/auth"; const auth = getAuth(app); auth.tenantId = "myTenantId1";Web
firebase.auth().tenantId = 'myTenantId1';
Çok öğeli kimlik doğrulamasını etkinleştirme
Firebase konsolunda Güvenlik > Kimlik doğrulama'ya gidin.
Sign-in method (Oturum açma yöntemi) sekmesindeki Advanced (Gelişmiş) bölümünde SMS Multi-factor Authentication'ı (SMS Çok Faktörlü Kimlik Doğrulama) etkinleştirin.
Uygulamanızı test etmek için kullanacağınız 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ı kaydetmeniz önemle tavsiye edilir.
Henüz yapmadıysanız uygulamanızın alan adını yetkilendirin:
Firebase konsolunda Security (Güvenlik) > Authentication (Kimlik Doğrulama) > Settings (Ayarlar) sekmesine gidin.
Yetkili alanlar bölümünde Alan ekle'yi tıklayın ve alanınızı ekleyin.
Kayıt modeli seçme
Uygulamanızın çok öğeli kimlik doğrulaması gerektirip gerektirmediğini ve kullanıcılarınızı nasıl ve ne zaman kaydettireceğinizi seçebilirsiniz. Yaygın kalıplardan bazıları şunlardır:
Kayıt işleminin bir parçası olarak kullanıcının ikinci faktörünü 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 faktör eklemek için atlanabilir bir seçenek sunun. Çok öğeli kimlik doğrulamayı zorunlu kılmak yerine teşvik etmek isteyen uygulamalar bu yaklaşımı tercih edebilir.
Kullanıcının, kaydolma ekranı yerine hesap veya profil yönetimi sayfasından ikinci faktör eklemesine olanak tanıyın. Bu sayede, kayıt sürecindeki zorluklar en aza indirilirken güvenliğe önem veren kullanıcılar için çok öğeli kimlik doğrulama kullanılabilir hale getirilir.
Kullanıcı, daha yüksek güvenlik gereksinimleri olan özelliklere erişmek istediğinde kademeli olarak ikinci bir faktör eklenmesini zorunlu kılma.
reCAPTCHA doğrulayıcıyı ayarlama
SMS kodları gönderebilmek için bir reCAPTCHA doğrulayıcı yapılandırmanız gerekir. Authentication, telefon numarası doğrulama isteklerinin uygulamanızın izin verilen alanlarından birinden gelmesini sağlayarak kötüye kullanımı önlemek için reCAPTCHA'yı kullanır.
reCAPTCHA istemcisini manuel olarak ayarlamanız gerekmez. İstemci SDK'sının RecaptchaVerifier nesnesi, gerekli tüm istemci anahtarlarını ve gizli anahtarları otomatik olarak oluşturup başlatır.
Görünmez reCAPTCHA'yı kullanma
RecaptchaVerifier nesnesi, genellikle herhangi bir etkileşim gerektirmeden kullanıcıyı doğrulayabilen görünmez reCAPTCHA'yı destekler. Görünmez reCAPTCHA kullanmak için size parametresi invisible olarak ayarlanmış bir RecaptchaVerifier oluşturun ve çok faktörlü kaydı başlatan kullanıcı arayüzü öğesinin kimliğini belirtin:
Web
import { RecaptchaVerifier, getAuth } from "firebase/auth";
const recaptchaVerifier = new RecaptchaVerifier(getAuth(), "sign-in-button", {
"size": "invisible",
"callback": function(response) {
// reCAPTCHA solved, you can proceed with
// phoneAuthProvider.verifyPhoneNumber(...).
onSolvedRecaptcha();
}
});
Web
var recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
'size': 'invisible',
'callback': function(response) {
// reCAPTCHA solved, you can proceed with phoneAuthProvider.verifyPhoneNumber(...).
onSolvedRecaptcha();
}
});
reCAPTCHA widget'ını kullanma
Görünür bir reCAPTCHA widget'ı kullanmak için widget'ı içerecek bir HTML öğesi oluşturun, ardından kullanıcı arayüzü kapsayıcısının kimliğini içeren bir RecaptchaVerifier nesnesi oluşturun. İsterseniz reCAPTCHA çözüldüğünde veya süresi dolduğunda çağrılan geri çağırmalar da ayarlayabilirsiniz:
Web
import { RecaptchaVerifier, getAuth } from "firebase/auth";
const recaptchaVerifier = new RecaptchaVerifier(
getAuth(),
"recaptcha-container",
// Optional reCAPTCHA parameters.
{
"size": "normal",
"callback": function(response) {
// reCAPTCHA solved, you can proceed with
// phoneAuthProvider.verifyPhoneNumber(...).
onSolvedRecaptcha();
},
"expired-callback": function() {
// Response expired. Ask user to solve reCAPTCHA again.
// ...
}
}
);
Web
var recaptchaVerifier = new firebase.auth.RecaptchaVerifier(
'recaptcha-container',
// Optional reCAPTCHA parameters.
{
'size': 'normal',
'callback': function(response) {
// reCAPTCHA solved, you can proceed with phoneAuthProvider.verifyPhoneNumber(...).
// ...
onSolvedRecaptcha();
},
'expired-callback': function() {
// Response expired. Ask user to solve reCAPTCHA again.
// ...
}
});
reCAPTCHA'yı önceden oluşturma
İsteğe bağlı olarak, iki faktörlü kaydı başlatmadan önce reCAPTCHA'yı önceden oluşturabilirsiniz:
Web
recaptchaVerifier.render()
.then(function (widgetId) {
window.recaptchaWidgetId = widgetId;
});
Web
recaptchaVerifier.render()
.then(function(widgetId) {
window.recaptchaWidgetId = widgetId;
});
render() çözümlendikten sonra, reCAPTCHA API'ye çağrı yapmak için kullanabileceğiniz reCAPTCHA widget kimliğini alırsınız:
var recaptchaResponse = grecaptcha.getResponse(window.recaptchaWidgetId);
RecaptchaVerifier, verify yöntemiyle bu mantığı soyutlar. Bu nedenle, grecaptcha değişkenini doğrudan işlemeniz gerekmez.
İkinci faktör kaydetme
Bir kullanıcı için yeni bir ikincil faktör kaydetmek istiyorsanız:
Kullanıcının kimliğini yeniden doğrulayın.
Kullanıcıdan telefon numarasını girmesini isteyin.
Önceki bölümde gösterildiği gibi reCAPTCHA doğrulayıcıyı başlatın. Bir RecaptchaVerifier örneği zaten yapılandırılmışsa bu adımı atlayın:
Web
import { RecaptchaVerifier, getAuth } from "firebase/auth"; const recaptchaVerifier = new RecaptchaVerifier( getAuth(),'recaptcha-container-id', undefined);Web
var recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container-id');Kullanıcı için çok faktörlü oturum oluşturun:
Web
import { multiFactor } from "firebase/auth"; multiFactor(user).getSession().then(function (multiFactorSession) { // ... });Web
user.multiFactor.getSession().then(function(multiFactorSession) { // ... })Kullanıcının telefon numarası ve çok öğeli oturumla bir
PhoneInfoOptionsnesnesi başlatın:Web
// Specify the phone number and pass the MFA session. const phoneInfoOptions = { phoneNumber: phoneNumber, session: multiFactorSession };Web
// Specify the phone number and pass the MFA session. var phoneInfoOptions = { phoneNumber: phoneNumber, session: multiFactorSession };Kullanıcının telefonuna doğrulama mesajı gönderme:
Web
import { PhoneAuthProvider } from "firebase/auth"; const phoneAuthProvider = new PhoneAuthProvider(auth); phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, recaptchaVerifier) .then(function (verificationId) { // verificationId will be needed to complete enrollment. });Web
var phoneAuthProvider = new firebase.auth.PhoneAuthProvider(); // Send SMS verification code. return phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, recaptchaVerifier) .then(function(verificationId) { // verificationId will be needed for enrollment completion. })Zorunlu olmasa da kullanıcılara önceden SMS mesajı alacaklarını ve standart ücretlerin geçerli olduğunu bildirmek en iyi uygulamadır.
İstek başarısız olursa reCAPTCHA'yı sıfırlayın ve kullanıcının tekrar deneyebilmesi için önceki adımı tekrarlayın. reCAPTCHA jetonları yalnızca bir kez kullanılabildiğinden,
verifyPhoneNumber()hata verdiğinde reCAPTCHA'yı otomatik olarak sıfırlayacağını unutmayın.Web
recaptchaVerifier.clear();Web
recaptchaVerifier.clear();SMS kodu gönderildikten sonra kullanıcıdan kodu doğrulamasını isteyin:
Web
// Ask user for the verification code. Then: const cred = PhoneAuthProvider.credential(verificationId, verificationCode);Web
// Ask user for the verification code. Then: var cred = firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);PhoneAuthCredentialile birMultiFactorAssertionnesnesi başlatın:Web
import { PhoneMultiFactorGenerator } from "firebase/auth"; const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(cred);Web
var multiFactorAssertion = firebase.auth.PhoneMultiFactorGenerator.assertion(cred);Kayıt işlemini 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 (ör. +1******1234) bu özellik, birden fazla ikinci faktörü olan kullanıcılar için kullanışlıdır.
Web
// Complete enrollment. This will update the underlying tokens // and trigger ID token change listener. multiFactor(user).enroll(multiFactorAssertion, "My personal phone number");Web
// Complete enrollment. This will update the underlying tokens // and trigger ID token change listener. user.multiFactor.enroll(multiFactorAssertion, 'My personal phone number');
Aşağıdaki kodda, ikinci faktör kaydetme işleminin eksiksiz bir örneği gösterilmektedir:
Web
import {
multiFactor, PhoneAuthProvider, PhoneMultiFactorGenerator,
RecaptchaVerifier, getAuth
} from "firebase/auth";
const recaptchaVerifier = new RecaptchaVerifier(getAuth(),
'recaptcha-container-id', undefined);
multiFactor(user).getSession()
.then(function (multiFactorSession) {
// Specify the phone number and pass the MFA session.
const phoneInfoOptions = {
phoneNumber: phoneNumber,
session: multiFactorSession
};
const phoneAuthProvider = new PhoneAuthProvider(auth);
// Send SMS verification code.
return phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, recaptchaVerifier);
}).then(function (verificationId) {
// Ask user for the verification code. Then:
const cred = PhoneAuthProvider.credential(verificationId, verificationCode);
const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(cred);
// Complete enrollment.
return multiFactor(user).enroll(multiFactorAssertion, mfaDisplayName);
});
Web
var recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container-id');
user.multiFactor.getSession().then(function(multiFactorSession) {
// Specify the phone number and pass the MFA session.
var phoneInfoOptions = {
phoneNumber: phoneNumber,
session: multiFactorSession
};
var phoneAuthProvider = new firebase.auth.PhoneAuthProvider();
// Send SMS verification code.
return phoneAuthProvider.verifyPhoneNumber(
phoneInfoOptions, recaptchaVerifier);
})
.then(function(verificationId) {
// Ask user for the verification code.
var cred = firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);
var multiFactorAssertion = firebase.auth.PhoneMultiFactorGenerator.assertion(cred);
// Complete enrollment.
return user.multiFactor.enroll(multiFactorAssertion, mfaDisplayName);
});
Tebrikler! Bir kullanıcı için ikinci bir kimlik doğrulama faktörünü başarıyla kaydettiniz.
Kullanıcıların ikinci bir faktörle oturum açması
Bir kullanıcının iki faktörlü SMS doğrulamasıyla oturum açmasını sağlamak için:
Kullanıcının ilk faktörüyle oturum açmasını sağlayın, ardından
auth/multi-factor-auth-requiredhatasını yakalayın. Bu hata, bir çözümleyici, kayıtlı ikinci faktörlerle ilgili ipuçları ve kullanıcının ilk faktörle kimliğini başarıyla doğruladığını kanıtlayan temel bir oturum içerir.Örneğin, kullanıcının ilk faktörü bir e-posta ve şifreyse:
Web
import { getAuth, signInWithEmailAndPassword, getMultiFactorResolver} from "firebase/auth"; const auth = getAuth(); signInWithEmailAndPassword(auth, email, password) .then(function (userCredential) { // User successfully signed in and is not enrolled with a second factor. }) .catch(function (error) { if (error.code == 'auth/multi-factor-auth-required') { // The user is a multi-factor user. Second factor challenge is required. resolver = getMultiFactorResolver(auth, error); // ... } else if (error.code == 'auth/wrong-password') { // Handle other errors such as wrong password. } });Web
firebase.auth().signInWithEmailAndPassword(email, password) .then(function(userCredential) { // User successfully signed in and is not enrolled with a second factor. }) .catch(function(error) { if (error.code == 'auth/multi-factor-auth-required') { // The user is a multi-factor user. Second factor challenge is required. resolver = error.resolver; // ... } else if (error.code == 'auth/wrong-password') { // Handle other errors such as wrong password. } ... });Kullanıcının ilk faktörü OAuth, SAML veya OIDC gibi bir birleşik sağlayıcıysa
signInWithPopup()ya dasignInWithRedirect()çağrıldıktan sonra hatayı yakalayın.Kullanıcının kayıtlı birden fazla ikincil faktörü varsa hangisini kullanacağını sorun:
Web
// Ask user which second factor to use. // You can get the masked phone number via resolver.hints[selectedIndex].phoneNumber // You can get the display name via resolver.hints[selectedIndex].displayName if (resolver.hints[selectedIndex].factorId === PhoneMultiFactorGenerator.FACTOR_ID) { // User selected a phone second factor. // ... } else if (resolver.hints[selectedIndex].factorId === TotpMultiFactorGenerator.FACTOR_ID) { // User selected a TOTP second factor. // ... } else { // Unsupported second factor. }Web
// Ask user which second factor to use. // You can get the masked phone number via resolver.hints[selectedIndex].phoneNumber // You can get the display name via resolver.hints[selectedIndex].displayName if (resolver.hints[selectedIndex].factorId === firebase.auth.PhoneMultiFactorGenerator.FACTOR_ID) { // User selected a phone second factor. // ... } else if (resolver.hints[selectedIndex].factorId === firebase.auth.TotpMultiFactorGenerator.FACTOR_ID) { // User selected a TOTP second factor. // ... } else { // Unsupported second factor. }Önceki bölümde gösterildiği gibi reCAPTCHA doğrulayıcıyı başlatın. Bir RecaptchaVerifier örneği zaten yapılandırılmışsa bu adımı atlayın:
Web
import { RecaptchaVerifier, getAuth } from "firebase/auth"; recaptchaVerifier = new RecaptchaVerifier(getAuth(), 'recaptcha-container-id', undefined);Web
var recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container-id');Kullanıcının telefon numarası ve çok öğeli oturumla bir
PhoneInfoOptionsnesnesi başlatın. Bu değerler,auth/multi-factor-auth-requiredhatasına iletilenresolvernesnesinde yer alır:Web
const phoneInfoOptions = { multiFactorHint: resolver.hints[selectedIndex], session: resolver.session };Web
var phoneInfoOptions = { multiFactorHint: resolver.hints[selectedIndex], session: resolver.session };Kullanıcının telefonuna doğrulama mesajı gönderme:
Web
// Send SMS verification code. const phoneAuthProvider = new PhoneAuthProvider(auth); phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, recaptchaVerifier) .then(function (verificationId) { // verificationId will be needed for sign-in completion. });Web
var phoneAuthProvider = new firebase.auth.PhoneAuthProvider(); // Send SMS verification code. return phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, recaptchaVerifier) .then(function(verificationId) { // verificationId will be needed for sign-in completion. })İstek başarısız olursa reCAPTCHA'yı sıfırlayın ve kullanıcının tekrar deneyebilmesi için önceki adımı tekrarlayın:
Web
recaptchaVerifier.clear();Web
recaptchaVerifier.clear();SMS kodu gönderildikten sonra kullanıcıdan kodu doğrulamasını isteyin:
Web
const cred = PhoneAuthProvider.credential(verificationId, verificationCode);Web
// Ask user for the verification code. Then: var cred = firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);PhoneAuthCredentialile birMultiFactorAssertionnesnesi başlatın:Web
const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(cred);Web
var multiFactorAssertion = firebase.auth.PhoneMultiFactorGenerator.assertion(cred);İkincil kimlik doğrulama işlemini tamamlamak için
resolver.resolveSignIn()numaralı telefonu 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:Web
// Complete sign-in. This will also trigger the Auth state listeners. resolver.resolveSignIn(multiFactorAssertion) .then(function (userCredential) { // userCredential will also contain the user, additionalUserInfo, 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, // userCredential.additionalUserInfo will contain data related to Google // provider that the user signed in with. // - user.credential contains the Google OAuth credential. // - user.credential.accessToken contains the Google OAuth access token. // - user.credential.idToken contains the Google OAuth ID token. });Web
// Complete sign-in. This will also trigger the Auth state listeners. resolver.resolveSignIn(multiFactorAssertion) .then(function(userCredential) { // userCredential will also contain the user, additionalUserInfo, 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, // userCredential.additionalUserInfo will contain data related to Google provider that // the user signed in with. // user.credential contains the Google OAuth credential. // user.credential.accessToken contains the Google OAuth access token. // user.credential.idToken contains the Google OAuth ID token. });
Aşağıdaki kodda, çok faktörlü bir kullanıcının oturum açma işleminin eksiksiz bir örneği gösterilmektedir:
Web
import {
getAuth,
getMultiFactorResolver,
PhoneAuthProvider,
PhoneMultiFactorGenerator,
RecaptchaVerifier,
signInWithEmailAndPassword
} from "firebase/auth";
const recaptchaVerifier = new RecaptchaVerifier(getAuth(),
'recaptcha-container-id', undefined);
const auth = getAuth();
signInWithEmailAndPassword(auth, email, password)
.then(function (userCredential) {
// User is not enrolled with a second factor and is successfully
// signed in.
// ...
})
.catch(function (error) {
if (error.code == 'auth/multi-factor-auth-required') {
const resolver = getMultiFactorResolver(auth, error);
// Ask user which second factor to use.
if (resolver.hints[selectedIndex].factorId ===
PhoneMultiFactorGenerator.FACTOR_ID) {
const phoneInfoOptions = {
multiFactorHint: resolver.hints[selectedIndex],
session: resolver.session
};
const phoneAuthProvider = new PhoneAuthProvider(auth);
// Send SMS verification code
return phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, recaptchaVerifier)
.then(function (verificationId) {
// Ask user for the SMS verification code. Then:
const cred = PhoneAuthProvider.credential(
verificationId, verificationCode);
const multiFactorAssertion =
PhoneMultiFactorGenerator.assertion(cred);
// Complete sign-in.
return resolver.resolveSignIn(multiFactorAssertion)
})
.then(function (userCredential) {
// User successfully signed in with the second factor phone number.
});
} else if (resolver.hints[selectedIndex].factorId ===
TotpMultiFactorGenerator.FACTOR_ID) {
// Handle TOTP MFA.
// ...
} else {
// Unsupported second factor.
}
} else if (error.code == 'auth/wrong-password') {
// Handle other errors such as wrong password.
}
});
Web
var resolver;
firebase.auth().signInWithEmailAndPassword(email, password)
.then(function(userCredential) {
// User is not enrolled with a second factor and is successfully signed in.
// ...
})
.catch(function(error) {
if (error.code == 'auth/multi-factor-auth-required') {
resolver = error.resolver;
// Ask user which second factor to use.
if (resolver.hints[selectedIndex].factorId ===
firebase.auth.PhoneMultiFactorGenerator.FACTOR_ID) {
var phoneInfoOptions = {
multiFactorHint: resolver.hints[selectedIndex],
session: resolver.session
};
var phoneAuthProvider = new firebase.auth.PhoneAuthProvider();
// Send SMS verification code
return phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, recaptchaVerifier)
.then(function(verificationId) {
// Ask user for the SMS verification code.
var cred = firebase.auth.PhoneAuthProvider.credential(
verificationId, verificationCode);
var multiFactorAssertion =
firebase.auth.PhoneMultiFactorGenerator.assertion(cred);
// Complete sign-in.
return resolver.resolveSignIn(multiFactorAssertion)
})
.then(function(userCredential) {
// User successfully signed in with the second factor phone number.
});
} else if (resolver.hints[selectedIndex].factorId ===
firebase.auth.TotpMultiFactorGenerator.FACTOR_ID) {
// Handle TOTP MFA.
// ...
} else {
// Unsupported second factor.
}
} else if (error.code == 'auth/wrong-password') {
// Handle other errors such as wrong password.
} ...
});
Tebrikler! Çok öğeli kimlik doğrulama kullanarak bir kullanıcının oturum açmasını sağladınız.
Sırada ne var?
- Admin SDK ile çok faktörlü kullanıcıları programatik olarak yönetin.