0Pricing
Firebase Auth & Realtime Database Apps · 课时

电话号码身份验证

使用 SMS 验证实现可靠的电话号码身份验证,确保用户安全访问

电话号码身份验证 是 CoddyKit 上的免费 Firebase Auth & Realtime Database Apps 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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.

  1. Go to the Firebase Console.
  2. Navigate to Authentication > Sign-in method.
  3. Enable the Phone provider.
  4. 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 RecaptchaVerifier to 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:

  1. The user enters their phone number into your app.
  2. Your app requests Firebase to send a verification code via SMS to that number.
  3. Firebase sends the SMS and returns a confirmationResult object to your app.
  4. The user receives the SMS and enters the code into your app.
  5. Your app uses the confirmationResult and 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 RecaptchaVerifier handles the challenge. Once solved, the callback is triggered, allowing signInWithPhoneNumber to 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 onAuthStateChanged listener 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!

常见问题解答

「电话号码身份验证」课时是免费的吗?

是的 — 「电话号码身份验证」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Firebase Auth & Realtime Database Apps 课程的其余内容,请升级到 CoddyKit PRO。 Firebase Auth & Realtime Database Apps 课程共包含 4 节课。

「电话号码身份验证」这节课中我会学到什么?

使用 SMS 验证实现可靠的电话号码身份验证,确保用户安全访问 你通过在浏览器中直接运行的动手代码来练习 Firebase Auth & Realtime Database Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Firebase Auth & Realtime Database Apps 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Firebase Auth & Realtime Database Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「电话号码身份验证」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Firebase Auth & Realtime Database Apps 课中编写并运行代码吗?

能。每节 Firebase Auth & Realtime Database Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 电话号码身份验证
  2. 多重身份验证(MFA)
  3. 自定义声明与安全规则
  4. 账户关联与身份验证提供商管理
← 返回 Firebase Auth & Realtime Database Apps