サーバサイド(Node.js)
Cloud Functionsにエンドポイントを作る
import {auth} from "firebase-admin"
exports.getCustomToken = functions.https.onCall((data, context) => {
if (!context.auth) {
throw new Error("not logged in.")
}
return auth().createCustomToken(data.userId)
.then((customToken) => {
// Send token back to client
return {customToken: customToken}
})
.catch((error) => {
console.log('Error creating custom token:', error);
throw error
})
})
クライアントサイド
通常ログイン成功時
import {signInWithEmailAndPassword} from "firebase/auth"
import {httpsCallable, getFunctions} from "firebase/functions"
// login with mail & password
signInWithEmailAndPassword(firebase.auth, email, password).then(r => {
// Custome Token エンドポイントへのリクエスト
const getCustomToken = httpsCallable<{userId: string}, { customToken: string }>(getFunctions(), 'getCustomToken')
getCustomToken({userId: user?.uid}).then(r => {
localStorage.setItem('customToken', r.data.customToken)
})
})
Tokenでログイン
import {getAuth, signInWithCustomToken} from "firebase/auth"
// localstorageからtoken取得
const token = localStorage.getItem("customToken")
if (token) {
signInWithCustomToken(getAuth(), token).then(r => {
if (r) {
// login 成功時の処理
}
})
}
留意事項
CustomTokenの有効期間
60分。
用途
サービス間のSSO
firebaseで認証しないサービスからfirebaseを用いたサービスへ遷移する際に遷移元でCustomeTokenを生成し、
これを用いてログイン可能。