Firebase PNV 공개 미리보기에서 Firebase Authentication는 로그인용 Firebase PNV 토큰을 직접 수락할 수 없습니다. 하지만 Firebase Authentication의 맞춤 인증 기능을 사용하여 사용자가 Firebase PNV로 로그인하도록 설정할 수 있습니다.
토큰 교환 엔드포인트 만들기
Firebase에서 맞춤 인증 솔루션을 구현하는 핵심 단계는 Firebase PNV 토큰을 수신하고, 유효성을 검사한 후 Firebase 맞춤 인증 토큰을 발급할 수 있는 엔드포인트를 만드는 것입니다. 그러면 애플리케이션에서 이 맞춤 토큰을 사용하여 사용자를 로그인할 수 있습니다.
이 엔드포인트는 모든 플랫폼에서 호스팅할 수 있지만 다음 예에서는 Firebase용 Cloud Functions를 사용하여 엔드포인트를 호스팅합니다.
Node.js
import { JwtVerifier } from "aws-jwt-verify";
import { getApp } from "firebase-admin/app";
import { getAuth, UserRecord } from "firebase-admin/auth";
import { onRequest } from "firebase-functions/https";
// Because we're deploying to Cloud Functions for Firebase, admin credentials
// are automatically available.
const app = getApp();
const authAdmin = getAuth(app);
// 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 });
// This Cloud Function is your token exchange endpoint. You pass the endpoint an
// FPNV token, and the Cloud Function verifies it and exchanges it for a
// Firebase Auth token corresponding to the same user.
export const signInWithFpnv = onRequest(async (req, res) => {
// Get the FPNV token from the request body.
const fpnvToken = req.body?;
if (!fpnvToken) {
res.sendStatus(400);
return;
}
let verifiedPhoneNumber;
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.
verifiedPhoneNumber = verifiedPayload.sub;
} catch {
// If verification fails, reject the token.
res.sendStatus(403);
return;
}
// Now that you have a verified phone number, look it up in your Firebase
// project's user database.
let user: UserRecord;
try {
// If a user account already exists with the phone number, retrieve it.
user = await authAdmin.getUserByPhoneNumber(verifiedPhoneNumber);
} catch {
// Otherwise, create a new user account using the phone number.
user = await authAdmin.createUser({phoneNumber: verifiedPhoneNumber});
}
// Finally, mint a Firebase custom auth token containing the UID of the user
// you looked up or created. Return this token to the caller.
const authToken = await authAdmin.createCustomToken(user.uid);
res.status(200).send(authToken);
return;
});
커스텀 인증 토큰으로 로그인
엔드포인트가 배포되면 다음 단계에 따라 사용자를 Firebase에 로그인시킵니다.
Firebase Phone Number Verification 시작하기 페이지에 설명된 흐름을 사용하여 Firebase PNV 토큰을 가져옵니다.
이 토큰을 Cloud Functions 엔드포인트에 전달합니다. 엔드포인트는 앱에 맞춤 인증 토큰을 반환하며, 이 토큰을
signInWithCustomToken()
에 전달할 수 있습니다.예를 들어 Retrofit을 사용하여 Firebase의
signin
메서드 중 하나와 인터페이스가 유사한signInWithFpnvToken()
메서드를 작성할 수 있습니다.Kotlin
class FpnvSigninExample { interface FPNVTokenExchangeService { @POST("signInWithFpnv") suspend fun signInWithFpnv(@Body fpnvToken: String): String } val retrofit = Retrofit.Builder() .baseUrl("https://example-project.cloudfunctions.net/") .build() val service: FPNVTokenExchangeService = retrofit.create(FPNVTokenExchangeService::class.java) suspend fun signInWithFpnvToken(fpnvToken: String): Task<AuthResult?> = coroutineScope { val authToken = service.signInWithFpnv(fpnvToken) return@coroutineScope Firebase.auth.signInWithCustomToken(authToken) } }