我正在尝试在 Node.js 服务器中使用 firebase(仅限身份验证),但即使开始,我也会遇到错误。
我相信我完全按照 Google 文档的“将 Firebase 添加到服务器”部分进行操作:https://firebase.google.com/docs/admin/setup。此外,我还阅读了 Google 搜索前几页中出现的所有 stackoverflow 以及 firebase-admin + nodejs 的多个教程网站。但似乎无法超越这里看似简单的一步。
我得到的具体错误是:
Error authenticating user: FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call initializeApp() first (app/no-app).
当我尝试以下操作时(再次尝试与文档显示的内容匹配):
.env:
GOOGLE_APPLICATION_CREDENTIALS="firebase-svc-acct.json"
(其中 firebase-svc-acct.json 是根据“在非 Google 环境中初始化 SDK”下的相同 google 文档获取的项目的服务帐户密钥)
index.ts(节点服务器入口):
...
import { initializeApp, applicationDefault } from "firebase-admin/app";
...
initializeApp({
credential: applicationDefault(),
});
AuthController.ts(临时测试,与快速路由器连接,为简洁起见,此处未显示,相信我,它在这里):
...
import { getAuth, signInWithEmailAndPassword } from "firebase/auth";
...
loginFirebaseTest = async (req: Request, res: Response): Promise<void> => {
const { email, password } = req.body;
const auth = getAuth(); // <------------------ Error is thrown here
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
console.log(
"Successfully authenticated user:",
userCredential.user.uid
);
res.status(200).json({ message: "User login successful" });
})
.catch((error) => {
console.log("Error authenticating user:", error);
res.status(401).json({ error: "Invalid credentials" });
res.send();
});
};
正如在对原始问题的评论中发现的那样,我只是认为 firebase 完全错误。与常见的是,当您烘焙自己的身份验证时,您不会将电子邮件+密码传递给 firebase 并交回令牌。客户端直接对 firebase 执行此操作。
因此,在后端,您只需开始接受/检查令牌 - 您不需要登录端点,您可以使用 nodejs 中的 firebase-admin 来完成此操作(firebase/auth 用于前端)。
了解如何在特定情况下进行身份验证超出了此处提出的问题的范围,但我发现 https://www.toptal.com/firebase/role-based-firebase-authentication 做了一个不错的介绍。