1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Firebase Custom Token認証

Last updated at Posted at 2022-01-09

サーバサイド(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を生成し、
これを用いてログイン可能。

他にも色々

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?