LoginSignup
36
28

More than 5 years have passed since last update.

Firebase FunctionsにAuthenticationの認証をつける

Last updated at Posted at 2018-09-07

リクエストを受けた時にfunctions側でFirebase Authenticationでログインしているかをチェックしたい。
ちょっとした内製のツールを作る時にG Suiteのアカウントで認証したい。

 Authenticationと連携する機能はないのでクライアント側で対応する

公式のサンプル
https://github.com/firebase/functions-samples/tree/Node-8/authorized-https-endpoint

クライアント側でAuthenticationにログインをしてtokenを作成して、
FunctionsのAPIにリクエストする際にHeaderとしてtokenを渡しています。
そのtokenをFunctions側で認証をチェックしていました。

クライアント側

javavscript
import axios from "axios"

firebase.auth().currentUser.getIdToken().then(function(token){
  axios.get("/api/xxxx", {
    headers: { 'Authorization': `Bearer ${token}`  }
  })
})

Functions側

javascript

const token = req.headers.authorization.split('Bearer ')[1];

try {
  const decodedToken = await admin.auth().verifyIdToken(token);
  console.log("success");
} catch (error) {
  console.error("error");
}

GAEみたいに簡単に強制的にログイン処理を挟めると思ったんですが難しいようですね。
IAM周りを使えば、できるのかもしれませんが。

36
28
1

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
36
28