开始在 Android 上使用 Firebase 电话号码验证

本页介绍了如何在 Android 应用中使用 Firebase Phone Number Verification。如需大致了解此功能,请参阅概览

本页详细介绍了如何使用统一的单次调用 API 与 Firebase PNV 集成。只需调用一个方法即可处理整个 Firebase PNV 用户流程,从征得用户同意到向 Firebase PNV 后端发出必要的网络调用。使用此方法可将集成步骤减少为单个方法调用。

建议大多数开发者使用此 API;不过,如果您有该库无法满足的特定要求,请参阅自定义 Firebase Phone Number Verification 流程页面,了解如何实现自定义流程。

准备工作

您必须在可公开访问的网站上发布应用的隐私权政策。在此页面上,您必须向用户说明您如何使用通过 Firebase Phone Number Verification 检索到的电话号码。当向用户请求同意与您的应用分享其电话号码时,Firebase PNV 库将链接到此页面。

1. 设置您的 Firebase 项目

  1. 将 Firebase 添加到您的 Android 项目(如果尚未添加)。

  2. Firebase PNV 需要使用 Blaze 方案。如果您尚未将项目升级为随用随付 Blaze 定价方案,请执行此操作。

  3. 如果您尚未在 Firebase 控制台中指定应用的 SHA-256 指纹,请在项目设置中指定。如需详细了解如何获取应用的 SHA-256 指纹,请参阅对客户端进行身份验证

  4. 在 Google Cloud 控制台中打开您的 Firebase 项目,然后启用 Firebase Phone Number Verification API

  5. 在控制台的凭据页面上,打开您的 Android API 密钥,然后将 Firebase Phone Number Verification API 添加到所选 API 的列表中。

2. 将 Firebase PNV 库添加到您的应用中

在您的模块(应用级)Gradle 文件(通常是 <project>/<app-module>/build.gradle.kts<project>/<app-module>/build.gradle)中,添加 Firebase Phone Number Verification 库的依赖项。

dependencies {
    // Add the dependency for the Firebase Phone Number Verification library
    implementation("com.google.firebase:firebase-pnv:16.0.0-beta01")
}

3. 可选:检查 Firebase PNV 支持情况

在启动验证流程之前,您可以检查设备及其 SIM 卡是否支持基于 API 的电话号码验证。这是一项预先检查,不需要征得用户同意。您可以根据此测试的结果来决定是启动 Firebase PNV 流程,还是使用其他电话号码验证方法(例如短信)。

如需检查设备是否兼容,请调用 getVerificationSupportInfo() 方法:

Kotlin

import com.google.firebase.pnv.FirebasePhoneNumberVerification
// Get an instance of the SDK.
val fpnv = FirebasePhoneNumberVerification.getInstance()

// Check all SIMs for support.
fpnv.getVerificationSupportInfo()
  .addOnSuccessListener { results ->
    if (results.any { it.isSupported() }) {
      // At least one SIM is supported; proceed with FPNV flow
    } else {
      // No SIMs are supported, so fall back to SMS verification.
    }
  }
  .addOnFailureListener { e ->
    // Handle error.
  }

getVerificationSupportInfo() 会返回一个 VerificationSupportResult 对象列表,每个 SIM 卡插槽对应一个对象。如果支持至少一张 SIM 卡,您可以继续执行 Firebase PNV 流程。

4. 启动验证流程

如需启动 Firebase PNV 流程,请创建一个新的 FirebasePhoneNumberVerification 实例,并传入 Activity 上下文。SDK 需要 Activity 上下文才能向用户显示意见征求界面。然后,调用对象的 getVerifiedPhoneNumber() 方法:

Kotlin

// Get an instance of the SDK _with an Activity context_:
val fpnv = FirebasePhoneNumberVerification.getInstance(this@MainActivity)

// Call getVerifiedPhoneNumber
fpnv.getVerifiedPhoneNumber("https://example.com/privacy-policy")
  .addOnSuccessListener { result ->
    val phoneNumber = result.getPhoneNumber()
    val token = result.getToken()
    // Verification successful. Send token to your backend.
  }
  .addOnFailureListener { e ->
    // Handle failures, such as the user declining consent or a network error.
  }

getVerifiedPhoneNumber() 方法会执行整个电话号码验证流程,包括:

  • 使用 Android Credential Manager 获取用户同意,以共享其电话号码。
  • Firebase PNV 后端发出请求。
  • 返回设备的已验证电话号码。

5. 使用 Firebase PNV 令牌

如果流程成功,getVerifiedPhoneNumber() 方法会返回经过验证的电话号码以及包含该电话号码的签名令牌。您可以在应用中使用这些数据,但必须遵守您的隐私权政策。

如果您在应用客户端之外使用经过验证的电话号码,则应传递令牌,而不是电话号码本身,以便在使用时验证其完整性。如需验证令牌,您可以使用任何 JWT 验证库。使用该库验证以下所有内容:

  • 令牌是使用 Firebase PNV JWKS 端点上发布的某个密钥进行签名的:

    https://fpnv.googleapis.com/v1beta/jwks
    
  • 受众群体声明和签发者声明包含您的 Firebase 项目编号,格式如下:

    https://fpnv.googleapis.com/projects/FIREBASE_PROJECT_NUMBER
    

    您可以在 Firebase 控制台的项目设置页面中找到您的 Firebase 项目编号。

  • 令牌未过期。

示例

举个简单的例子,以下 Express.js 应用会从 HTTP POST 请求接收 Firebase PNV 令牌,并使用 JWT 验证库来检查令牌的签名和声明:

Node.js

import express from "express";
import { JwtVerifier } from "aws-jwt-verify";

// Find your Firebase project number in the Firebase console.
const FIREBASE_PROJECT_NUMBER = "123456789";

// The issuer and audience claims of the FPNV token are specific to your
// project.
const issuer = `https://fpnv.googleapis.com/projects/${FIREBASE_PROJECT_NUMBER}`;
const audience = `https://fpnv.googleapis.com/projects/${FIREBASE_PROJECT_NUMBER}`;

// The JWKS URL contains the current public signing keys for FPNV tokens.
const jwksUri = "https://fpnv.googleapis.com/v1beta/jwks";

// Configure a JWT verifier to check the following:
// - The token is signed by Google
// - The issuer and audience claims match your project
// - The token has not yet expired (default behavior)
const fpnvVerifier = JwtVerifier.create({ issuer, audience, jwksUri });

const app = express();

app.post('/verifiedPhoneNumber', async (req, res) => {
    if (!req.body) return res.sendStatus(400);
    // Get the token from the body of the request.
    const fpnvToken = req.body;
    try {
        // Attempt to verify the token using the verifier configured above.
        const verifiedPayload = await fpnvVerifier.verify(fpnvToken);

        // If verification succeeds, the subject claim of the token contains the
        // verified phone number. You can use this value however it's needed by
        // your app.
        const verifiedPhoneNumber = verifiedPayload.sub;
        // (Do something with it...)

        return res.sendStatus(200);
    } catch {
        // If verification fails, reject the token.
        return res.sendStatus(400);
    }
});

app.listen(3000);

登录 Firebase 应用

如需查看在 Firebase Authentication 登录流程中使用 Firebase PNV 令牌的示例,请参阅使用 Firebase Phone Number Verification 进行 Firebase 身份验证页面。