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

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

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

  • โทเค็นลงชื่อโดยใช้คีย์รายการใดรายการหนึ่งที่เผยแพร่ในปลายทาง Firebase PNV JWKS ด้วยอัลกอริทึม 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);