ยืนยันโทเค็น PNV ของ Firebase

เมื่อไลบรารี Firebase PNV ยืนยันหมายเลขโทรศัพท์ของอุปกรณ์เรียบร้อยแล้ว ระบบจะแสดงหมายเลขโทรศัพท์ที่ยืนยันแล้วและโทเค็นที่ลงชื่อซึ่งมีหมายเลขโทรศัพท์ดังกล่าว หากคุณใช้หมายเลขโทรศัพท์ที่ยืนยันแล้วนอกไคลเอ็นต์แอป คุณควรส่งโทเค็นแทนหมายเลขโทรศัพท์ เพื่อให้คุณสามารถยืนยันความสมบูรณ์ของโทเค็นเมื่อใช้งานได้ หากต้องการยืนยันโทเค็น คุณสามารถใช้ไลบรารีการยืนยัน JWT ใดก็ได้ ใช้ไลบรารีเพื่อยืนยันสิ่งต่อไปนี้ทั้งหมด

  • ส่วนหัว typ ตั้งค่าเป็น JWT

  • โทเค็นได้รับการรับรองโดยใช้คีย์ใดคีย์หนึ่งที่เผยแพร่ที่ปลายทาง JWKS Firebase PNV ด้วยอัลกอริทึม ES256

    https://fpnv.googleapis.com/v1beta/jwks
    
  • การอ้างสิทธิ์ผู้ออกมีหมายเลขโปรเจ็กต์ Firebase และอยู่ในรูปแบบต่อไปนี้

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

    คุณดูหมายเลขโปรเจ็กต์ Firebase ได้ในแท็บ การตั้งค่า > ทั่วไปของคอนโซล Firebase

  • การอ้างสิทธิ์กลุ่มเป้าหมายคือรายการที่มีหมายเลขโปรเจ็กต์ Firebase และรหัสโปรเจ็กต์ และอยู่ในรูปแบบต่อไปนี้

    [
      https://fpnv.googleapis.com/projects/FIREBASE_PROJECT_NUMBER,
      https://fpnv.googleapis.com/projects/FIREBASE_PROJECT_ID,
    ]
    
  • โทเค็นยังไม่หมดอายุ

ตัวอย่าง

ตัวอย่างเช่น แอป Express.js ต่อไปนี้จะได้รับโทเค็น Firebase PNV จากคำขอ HTTP POST และใช้ไลบรารีการยืนยัน 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
        previously.
        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);