Android पर Firebase फ़ोन नंबर की पुष्टि करने के फ़्लो को पसंद के मुताबिक बनाना

Firebase Phone Number Verification का इस्तेमाल शुरू करें पेज पर, getVerifiedPhoneNumber() तरीके का इस्तेमाल करके Firebase PNV के साथ इंटिग्रेट करने का तरीका बताया गया है. यह तरीका, Firebase PNV के पूरे फ़्लो को मैनेज करता है. इसमें उपयोगकर्ता की सहमति लेना और Firebase PNV के बैकएंड पर ज़रूरी नेटवर्क कॉल करना शामिल है.

ज़्यादातर डेवलपर के लिए, सिंगल-मेथड एपीआई (getVerifiedPhoneNumber()) का इस्तेमाल करने का सुझाव दिया जाता है. हालांकि, अगर आपको Android Credential Manager के साथ इंटरैक्शन पर ज़्यादा कंट्रोल चाहिए, तो Firebase PNV लाइब्रेरी ये दो तरीके भी उपलब्ध कराती है. उदाहरण के लिए, फ़ोन नंबर के साथ-साथ अन्य क्रेडेंशियल का अनुरोध करने के लिए. इनमें से हर तरीका, Firebase PNV बैकएंड के साथ अलग-अलग इंटरैक्शन को हैंडल करता है:

  • getDigitalCredentialPayload() को सर्वर से साइन किया गया एक अनुरोध मिलता है. इसका इस्तेमाल, क्रेडेंशियल मैनेजर को चालू करने के लिए किया जाएगा.
  • exchangeCredentialResponseForPhoneNumber(), Credential Manager से मिले जवाब को ऐसे हस्ताक्षरित टोकन के लिए बदलता है जिसमें पुष्टि किया गया फ़ोन नंबर शामिल होता है.

इनमें से हर तरीके को कॉल करने के बीच, Android के Credential Manager API के साथ इंटरैक्शन को मैनेज करने की ज़िम्मेदारी आपकी होती है. इस पेज पर, तीन हिस्सों वाले इस फ़्लो को लागू करने के तरीके के बारे में खास जानकारी दी गई है.

शुरू करने से पहले

अपना Firebase प्रोजेक्ट सेट अप करें और शुरू करें पेज पर बताए गए तरीके से, Firebase PNV डिपेंडेंसी इंपोर्ट करें.

1. डिजिटल क्रेडेंशियल के अनुरोध का पेलोड पाना

डिवाइस का फ़ोन नंबर पाने का अनुरोध जनरेट करने के लिए, getDigitalCredentialPayload() तरीके का इस्तेमाल करें. अगले चरण में, यह अनुरोध Credential Manager API के साथ आपके इंटरैक्शन का पेलोड होगा.

// 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. क्रेडेंशियल मैनेजर का इस्तेमाल करके, डिजिटल क्रेडेंशियल का अनुरोध करना

इसके बाद, अनुरोध को क्रेडेंशियल मैनेजर को भेजें.

इसके लिए, आपको अनुरोध के पेलोड को DigitalCredential API के अनुरोध में रैप करना होगा. इस अनुरोध में वही नॉनस शामिल होना चाहिए जिसे आपने getDigitalCredentialPayload() को पास किया था.

// 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 का इस्तेमाल करके अनुरोध किया जा सकता है:

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 कॉल पूरा हो जाता है, तो इसके जवाब में एक डिजिटल क्रेडेंशियल शामिल होगा. इसे इस उदाहरण में दिए गए कोड का इस्तेमाल करके निकाला जा सकता है:

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 टोकन के लिए एक्सचेंज करना

आखिर में, पुष्टि किए गए फ़ोन नंबर और exchangeCredentialResponseForPhoneNumber() टोकन के लिए, डिजिटल क्रेडेंशियल के जवाब को बदलने के लिए exchangeCredentialResponseForPhoneNumber() तरीके का इस्तेमाल करें:Firebase PNV

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

4. Firebase PNV टोकन की पुष्टि की जा रही है

अगर पुष्टि करने की प्रोसेस पूरी हो जाती है, तो getVerifiedPhoneNumber() तरीके से पुष्टि किया गया फ़ोन नंबर और उस नंबर वाला हस्ताक्षर किया गया टोकन मिलता है. इस डेटा का इस्तेमाल अपने ऐप्लिकेशन में किया जा सकता है. हालांकि, इसके लिए आपको अपनी निजता नीति में इसकी जानकारी देनी होगी.

अगर आपको पुष्टि किए गए फ़ोन नंबर का इस्तेमाल ऐप्लिकेशन क्लाइंट के बाहर करना है, तो आपको फ़ोन नंबर के बजाय टोकन पास करना चाहिए. इससे, इस्तेमाल करते समय इसकी पुष्टि की जा सकेगी. टोकन की पुष्टि करने के लिए, आपको दो एंडपॉइंट लागू करने होंगे:

  • नॉनस जनरेट करने वाला एंडपॉइंट
  • टोकन की पुष्टि करने वाला एंडपॉइंट

इन एंडपॉइंट को लागू करने का तरीका आपके ऊपर है. यहां दिए गए उदाहरणों में, Node.js और Express का इस्तेमाल करके इन्हें लागू करने का तरीका बताया गया है.

नॉनस जनरेट किए जा रहे हैं

यह एंडपॉइंट, एक बार इस्तेमाल की जा सकने वाली वैल्यू जनरेट करता है और उन्हें कुछ समय के लिए सेव करता है. इन वैल्यू को नॉनस कहा जाता है. इनका इस्तेमाल, आपके एंडपॉइंट पर रीप्ले अटैक को रोकने के लिए किया जाता है. उदाहरण के लिए, आपके पास इस तरह से तय किया गया एक्सप्रेस रूट हो सकता है:

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

यह वह एंडपॉइंट है जिसे पहले चरण में मौजूद प्लेसहोल्डर फ़ंक्शन, fetchNonceFromYourServer(), कॉल करेगा. यह नॉनस, क्लाइंट की ओर से किए गए अलग-अलग नेटवर्क कॉल के ज़रिए आगे बढ़ता है. इसके बाद, यह Firebase PNV टोकन में आपके सर्वर पर वापस आ जाता है. अगले चरण में, आपको यह पुष्टि करनी होगी कि टोकन में आपके जनरेट किया गया नॉनस मौजूद है.

टोकन की पुष्टि करना

यह एंडपॉइंट, आपके क्लाइंट से Firebase PNV टोकन पाता है और उनकी पुष्टि करता है. किसी टोकन की पुष्टि करने के लिए, आपको यह देखना होगा कि:

  • टोकन पर, Firebase PNV JWKS एंडपॉइंट पर पब्लिश की गई किसी एक कुंजी का इस्तेमाल करके हस्ताक्षर किया जाता है:

    https://fpnv.googleapis.com/v1beta/jwks
    
  • ऑडियंस और जारी करने वाले के दावों में, आपका Firebase प्रोजेक्ट नंबर शामिल होता है. साथ ही, यह इस फ़ॉर्मैट में होता है:

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

    आपको Firebase प्रोजेक्ट का नंबर, Firebase कंसोल के प्रोजेक्ट सेटिंग पेज पर मिल सकता है.

  • टोकन की समयसीमा खत्म नहीं हुई है.

  • टोकन में मान्य नॉनस शामिल है. कोई नॉन्स तब मान्य होता है, जब:

    • आपने इसे जनरेट किया हो. इसका मतलब है कि यह उस परसिस्टेंस मैकेनिज़्म में मौजूद हो जिसका इस्तेमाल किया जा रहा है
    • इसका इस्तेमाल पहले न किया गया हो
    • इसकी समयसीमा खत्म नहीं हुई है

उदाहरण के लिए, 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 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);
    }
});