전화번호 인증
안전한 사용자 액세스를 위해 SMS 인증을 사용하는 강력한 전화번호 인증을 구현합니다.
전화번호 인증은(는) CoddyKit의 무료 Firebase Auth & Realtime Database Apps 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Firebase Auth & Realtime Database Apps 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Firebase Auth & Realtime Database Apps 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Secure Login with Phone Numbers
Phone number authentication allows users to sign in to your app using their mobile phone number. It's a secure and convenient method, especially for users who prefer not to create traditional email/password accounts or use social logins.
- Accessibility: Many users find it easy to use.
- Security: Leverages SMS for verification, adding a layer of security.
- No Passwords: Reduces password fatigue and forgotten password issues.
Enabling Phone Authentication
Before you can use phone number authentication in your app, you need to enable it in your Firebase project settings.
- Go to the Firebase Console.
- Navigate to Authentication > Sign-in method.
- Enable the Phone provider.
- Optionally, specify which phone numbers are allowed for testing.
This step tells Firebase that your project will support phone sign-ins.
Client-Side Preparation
To use phone authentication, your client-side application needs to be set up correctly. This often involves specific mechanisms to verify the user isn't a bot.
- Web: You'll need to use a
RecaptchaVerifierto protect against abuse. - Android: Firebase uses SafetyNet for device verification.
- iOS: Firebase uses DeviceCheck for device verification.
These checks ensure that the phone number verification requests are coming from legitimate app instances.
The Verification Flow
The phone number authentication process typically follows these steps:
- The user enters their phone number into your app.
- Your app requests Firebase to send a verification code via SMS to that number.
- Firebase sends the SMS and returns a
confirmationResultobject to your app. - The user receives the SMS and enters the code into your app.
- Your app uses the
confirmationResultand the SMS code to sign the user in.
Let's see how to implement this.
Initiating Phone Verification (Web)
On the web, you'll use firebase.auth().signInWithPhoneNumber(). It requires a phone number and a RecaptchaVerifier instance. The confirmationResult is crucial for the next step.
/* Assuming Firebase SDK is initialized and 'auth' is firebase.auth() */
// 1. Prepare reCAPTCHA verifier (invisible is common for better UX)
const appVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container', {
'size': 'invisible',
'callback': (response) => {
// reCAPTCHA solved, now signInWithPhoneNumber can proceed
console.log('reCAPTCHA solved!');
}
});
// 2. Send the verification code
function sendVerificationCode(phoneNumber) {
firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
.then((confirmationResult) => {
// SMS sent. Save this object globally to confirm the code later.
window.confirmationResult = confirmationResult;
console.log('Verification code sent to ' + phoneNumber);
}).catch((error) => {
console.error('Error sending SMS:', error.message);
});
}
// Example usage (in a real app, this would be triggered by a button click)
// sendVerificationCode('+15551234567');
console.log("Function 'sendVerificationCode' defined. Call it with a phone number (e.g., sendVerificationCode('+15551234567')) to try.");Protecting with reCAPTCHA
For web applications, Firebase Phone Auth requires reCAPTCHA verification to prevent abuse, like automated bots attempting to send SMS messages.
- You need an HTML element (e.g., a
div) with a specific ID (like'recaptcha-container') where reCAPTCHA can render, even if it's invisible. - The
RecaptchaVerifierhandles the challenge. Once solved, the callback is triggered, allowingsignInWithPhoneNumberto proceed.
It's an important security measure for web clients.
Confirming the SMS Code
Once the user receives the SMS code and enters it, you use the confirmationResult object (saved from the previous step) to verify the code and complete the sign-in.
/* Assuming 'window.confirmationResult' holds the object from signInWithPhoneNumber */
function verifySmsCode(smsCode) {
if (window.confirmationResult) {
window.confirmationResult.confirm(smsCode)
.then((result) => {
// User signed in successfully!
const user = result.user;
console.log('User signed in with phone number:', user.phoneNumber);
console.log('User UID:', user.uid);
}).catch((error) => {
// User couldn't sign in (e.g., invalid code)
console.error('Error verifying SMS code:', error.message);
});
} else {
console.error('No confirmationResult found. Send SMS first!');
}
}
// Example usage (in a real app, this would be triggered by a button click)
// verifySmsCode('123456'); // Replace with the actual code received via SMS
console.log("Function 'verifySmsCode' defined. Call it with an SMS code (e.g., verifySmsCode('123456')) after sending a verification code.");Accessing User Information
After a successful phone number sign-in, the user's information is available through the firebase.auth().currentUser object, just like any other authentication method.
- You can access their
uid,phoneNumber, and other profile details. - Use the
onAuthStateChangedlistener to monitor the user's login state across your application.
This allows you to personalize content and manage user sessions.
Handling Common Errors
It's important to anticipate and handle errors gracefully to provide a good user experience. Some common errors with phone authentication include:
auth/invalid-phone-number: The provided phone number is not valid.auth/missing-verification-code: The user didn't enter a code or it was empty.auth/invalid-verification-code: The entered SMS code is incorrect.auth/captcha-check-failed: reCAPTCHA verification failed (web).auth/too-many-requests: Too many verification attempts from the same device/IP.
Always display user-friendly messages for these errors.
Verify Your Knowledge
Which of the following is REQUIRED for phone number authentication in a web application?
Phone Auth Summary
You've learned how to implement phone number authentication with Firebase!
- Enable the provider in the Firebase Console.
- Set up client-side checks (reCAPTCHA for web).
- Initiate verification with
signInWithPhoneNumber(). - Confirm the SMS code using the
confirmationResult. - Handle various error scenarios gracefully.
Phone auth offers a great balance of security and convenience for your users. Practice implementing it in your projects!
자주 묻는 질문
“전화번호 인증” 강의는 무료인가요?
네 — “전화번호 인증” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Firebase Auth & Realtime Database Apps 강의 전체를 잠금 해제할 수 있습니다. Firebase Auth & Realtime Database Apps 강의에는 총 4개의 강의가 포함되어 있습니다.
“전화번호 인증”에서 뭘 배우나요?
안전한 사용자 액세스를 위해 SMS 인증을 사용하는 강력한 전화번호 인증을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 Firebase Auth & Realtime Database Apps을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Firebase Auth & Realtime Database Apps을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Firebase Auth & Realtime Database Apps은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“전화번호 인증” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Firebase Auth & Realtime Database Apps 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Firebase Auth & Realtime Database Apps 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.