התאמה אישית של תהליך אימות מספר הטלפון ב-Firebase ב-Android

בדף תחילת העבודה עם Firebase Phone Number Verification מוסבר איך לשלב את Firebase PNV באמצעות השיטה getVerifiedPhoneNumber(), שמטפלת בכל התהליך של Firebase PNV, החל מקבלת הסכמה מהמשתמש ועד לביצוע הקריאות הנדרשות לרשת לקצה העורפי של Firebase PNV.

לרוב המפתחים מומלץ להשתמש ב-API עם שיטה אחת (getVerifiedPhoneNumber()). עם זאת, אם אתם צריכים שליטה מפורטת יותר באינטראקציה עם Android Credential Manager – לדוגמה, כדי לבקש פרטי כניסה אחרים יחד עם מספר הטלפון – הספרייה Firebase PNV מספקת גם את שתי השיטות הבאות, שכל אחת מהן מטפלת באינטראקציה אחרת עם הקצה העורפי של Firebase PNV:

  • ‫getDigitalCredentialPayload() מקבל בקשה חתומה על ידי השרת, שבה תשתמשו כדי להפעיל את Credential Manager.
  • ‫exchangeCredentialResponseForPhoneNumber() מחליפה את התגובה מ-Credential Manager באסימון חתום שמכיל את מספר הטלפון המאומת. החיוב יתבצע בשלב הזה.

בין הקריאות לכל אחת מהשיטות האלה, אתם אחראים לטפל באינטראקציה עם ממשקי ה-API של Credential Manager ב-Android. בדף הזה מוסבר איך מטמיעים את התהליך הזה, שמורכב משלושה חלקים.

לפני שמתחילים

מגדירים את הפרויקט ב-Firebase ומייבאים את יחסי התלות של Firebase PNV, כמו שמתואר בדף תחילת העבודה.

1. קבלת המטען הייעודי (payload) של הבקשה לאישור דיגיטלי

מפעילים את השיטה getDigitalCredentialPayload() כדי ליצור בקשה למספר הטלפון של המכשיר. בשלב הבא, הבקשה הזו תהיה המטען הייעודי (payload) של האינטראקציה עם Credential Manager API.

Kotlin

// This instance does not require an Activity context.
val fpnv = FirebasePhoneNumberVerification.getInstance()

// Your request should include a nonce, which will propagate through the flow
// and be present in the final response from FPNV. See the section "Verifying
// the Firebase PNV token" for details on generating and verifying this.
val nonce = fetchNonceFromYourServer()

fpnv.getDigitalCredentialPayload(nonce, "https://example.com/privacy-policy")
  .addOnSuccessListener { fpnvDigitalCredentialPayload ->
    // Use the payload in the next step.
    // ...
  }
  .addOnFailureListener { e -> /* Handle payload fetch failure */ }

2. שליחת בקשה לאישור דיגיטלי באמצעות Credential Manager

בשלב הבא, מעבירים את הבקשה אל Credential Manager.

כדי לעשות את זה, צריך לעטוף את המטען הייעודי (payload) של הבקשה בבקשת DigitalCredential API. הבקשה הזו חייבת לכלול את אותו צופן חד-פעמי (nonce) שהעברתם אל getDigitalCredentialPayload().

Kotlin

// This example uses string interpolation for clarity, but you should use some kind of type-safe
// serialization method.
fun buildDigitalCredentialRequestJson(nonce: String, fpnvDigitalCredentialPayload: String) = """
    {
      "requests": [
        {
          "protocol": "openid4vp-v1-unsigned",
          "data": {
            "response_type": "vp_token",
            "response_mode": "dc_api",
            "nonce": "$nonce",
            "dcql_query": { "credentials": [$fpnvDigitalCredentialPayload] }
          }
        }
      ]
    }
""".trimIndent()

אחרי שעושים את זה, אפשר לשלוח את הבקשה באמצעות Credential Manager API:

Kotlin

suspend fun makeFpnvRequest(
  context: Activity, nonce: String, fpnvDigitalCredentialPayload: String): GetCredentialResponse {
  // Helper function to build the digital credential request (defined above).
  // Pass the same nonce you passed to getDigitalCredentialPayload().
  val digitalCredentialRequestJson =
    buildDigitalCredentialRequestJson(nonce, fpnvDigitalCredentialPayload)

  // CredentialManager requires an Activity context.
  val credentialManager = CredentialManager.create(context)

  // Build a Credential Manager request that includes the Firebase PNV option. Note that
  // you can't combine the digital credential option with other options.
  val request = GetCredentialRequest.Builder()
    .addCredentialOption(GetDigitalCredentialOption(digitalCredentialRequestJson))
    .build()

  // getCredential is a suspend function, so it must run in a coroutine scope,
  val cmResponse: GetCredentialResponse = try {
    credentialManager.getCredential(context, request)
  } catch (e: GetCredentialException) {
    // If the user cancels the operation, the feature isn't available, or the
    // SIM doesn't support the feature, a GetCredentialCancellationException
    // will be returned. Otherwise, a GetCredentialUnsupportedException will
    // be returned with details in the exception message.
    throw e
  }
  return cmResponse
}

אם הקריאה ל-Credential Manager תצליח, התגובה תכלול פרטי כניסה דיגיטליים, שאפשר לחלץ באמצעות קוד כמו בדוגמה הבאה:

Kotlin

val dcApiResponse = extractApiResponse(cmResponse)
fun extractApiResponse(response: GetCredentialResponse): String {
  val credential = response.credential
  when (credential) {
    is DigitalCredential -> {
      val json = JSONObject(credential.credentialJson)
      val firebaseJwtArray =
          json.getJSONObject("data").getJSONObject("vp_token").getJSONArray("firebase")
      return firebaseJwtArray.getString(0)

    }
    else -> {
      // Handle any unrecognized credential type here.
      Log.e(TAG, "Unexpected type of credential ${credential.type}")
    }
  }
}

3. החלפת התגובה של פרטי הכניסה הדיגיטליים באסימון של Firebase PNV

לבסוף, קוראים ל-method‏ exchangeCredentialResponseForPhoneNumber() כדי להחליף את התגובה של פרטי הכניסה הדיגיטליים במספר הטלפון המאומת ובאסימון Firebase PNV:

Kotlin

fpnv.exchangeCredentialResponseForPhoneNumber(dcApiResponse)
  .addOnSuccessListener { result ->
    val phoneNumber = result.getPhoneNumber()
    // Verification successful
  }
  .addOnFailureListener { e -> /* Handle exchange failure */ }

השלב הזה יפעיל את החיוב כשהוא יושלם בהצלחה ומספר הטלפון המאומת יוחזר לאפליקציה.

4. אימות הטוקן של Firebase PNV

אם התהליך מצליח, ה-method‏ getVerifiedPhoneNumber() מחזירה את מספר הטלפון המאומת ואסימון חתום שמכיל אותו. אתם יכולים להשתמש בנתונים האלה באפליקציה שלכם, בהתאם למדיניות הפרטיות שלכם.

אם אתם משתמשים במספר הטלפון המאומת מחוץ ללקוח האפליקציה, כדאי להעביר את האסימון במקום את מספר הטלפון עצמו, כדי שתוכלו לאמת את התקינות שלו כשתשתמשו בו. כדי לאמת טוקנים, צריך להטמיע שתי נקודות קצה (endpoints):

  • נקודת קצה (endpoint) ליצירת מספר חד-פעמי (nonce)
  • נקודת קצה (endpoint) לאימות טוקנים

אתם יכולים להטמיע את נקודות הקצה האלה איך שאתם רוצים. בדוגמאות הבאות מוסבר איך להטמיע אותן באמצעות Node.js ו-Express.

יצירת מספרים חד-פעמיים (nonce)

נקודת הקצה הזו אחראית ליצירה ולאחסון זמני של ערכים לשימוש חד-פעמי שנקראים מספרים חד-פעמיים (nonce), שמשמשים למניעת התקפות שליחה מחדש נגד נקודות הקצה שלכם. לדוגמה, יכול להיות שהגדרתם נתיב Express כזה:

Node.js

app.get('/fpnvNonce', async (req, res) => {
    const nonce = crypto.randomUUID();

    // TODO: Save the nonce to a database, key store, etc.
    // You should also assign the nonce an expiration time and periodically
    // clear expired nonces from your database.
    await persistNonce({
        nonce,
        expiresAt: Date.now() + 180000, // Give it a short duration.
    });

    // Return the nonce to the caller.
    res.send({ nonce });
});

זו נקודת הקצה שאליה תתבצע הקריאה מהפונקציה של ה-placeholder,‏ fetchNonceFromYourServer(), בשלב 1. ה-nonce יופץ דרך הקריאות השונות לרשת שהלקוח מבצע, ובסופו של דבר יחזור לשרת שלכם באסימון Firebase PNV. בשלב הבא, מוודאים שהאסימון מכיל מספר חד-פעמי שיצרתם.

אימות טוקנים

נקודת הקצה הזו מקבלת אסימוני Firebase PNV מהלקוח ומאמתת את האותנטיות שלהם. כדי לאמת טוקן, צריך לבדוק:

  • הכותרת typ מוגדרת ל-JWT.

  • האסימון נחתם באמצעות אחד מהמפתחות שפורסמו בנקודת הקצה (endpoint) של Firebase PNV JWKS עם אלגוריתם ES256:

    https://fpnv.googleapis.com/v1beta/jwks
    
  • הצהרות המנפיק מכילות את מספר הפרויקט ב-Firebase, בפורמט הבא:

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

    מספר הפרויקט ב-Firebase מופיע בכרטיסייה Settings > General במסוף Firebase.

  • הצהרת הקהל היא רשימה שמכילה את מספר הפרויקט ואת מזהה הפרויקט ב-Firebase, בפורמט הבא:

    [
      https://fpnv.googleapis.com/projects/FIREBASE_PROJECT_NUMBER,
      https://fpnv.googleapis.com/projects/FIREBASE_PROJECT_ID,
    ]
    
  • הטוקן בתוקף.

  • האסימון מכיל מספר חד-פעמי (nonce) תקין. ה-nonce תקין אם:

    • אתם יצרתם אותו (כלומר, אפשר למצוא אותו במנגנון השמירה שבו אתם משתמשים)
    • הוא לא היה בשימוש בעבר
    • הוא בתוקף

לדוגמה, ההטמעה של Express עשויה להיראות כך:

Node.js

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 begavior)
const fpnvVerifier = JwtVerifier.create({ issuer, audience, jwksUri });

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);

        // Now that you've verified the signature and claims, verify the nonce.
        // TODO: Try to look up the nonce in your database and remove it if it's
        // found; if it's not found or it's expired, throw an error.
        await testAndRemoveNonce(verifiedPayload.nonce);

        // Only after verifying the JWT signature, claims, and nonce, get the
        // verified phone number from the subject claim.
        // 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);
    }
});