【问题标题】:How do I create custom tokens in Firebase using React?如何使用 React 在 Firebase 中创建自定义令牌?
【发布时间】:2021-11-17 14:22:33
【问题描述】:

我正在尝试创建一个自定义令牌以使用用户名登录用户。我浏览了一些文档https://firebase.google.com/docs/auth/admin/create-custom-tokens#web,这些文档通过How to provide user login with a username and NOT an email? 链接到我,我看到我需要添加

使用 Firebase Admin SDK 创建自定义令牌

使用客户端上的自定义令牌登录

目前,我可以根据文档了解需要包含哪些内容,但我不确定这将在源代码中的什么位置。我在哪里添加文档中的代码?这是 userUser.js 文件的源代码,以防万一。

import { useEffect, useState } from "react";
import { useRouter } from "next/router";
import firebase from "firebase/app";
import "firebase/auth";

import initFirebase from "../../config";
import {
  removeUserCookie,
  setUserCookie,
  getUserFromCookie,
} from "./userCookie";

initFirebase();

export const mapUserData = async (user) => {
  const { uid, email } = user;
  const token = await user.getIdToken(true);
  return {
    id: uid,
    email,
    token,
  };
};

const useUser = () => {
  const [user, setUser] = useState();
  const router = useRouter();

  // this is most likely where the custom token for
  // username goes
  const logout = async () => {
    return firebase
      .auth()
      .signOut()
      .then(() => {
        router.push("/");
      })
      .catch((e) => {
        console.error(e);
      });
  };

  useEffect(() => {
    const cancelAuthListener = firebase
      .auth()
      .onIdTokenChanged(async (userToken) => {
        if (userToken) {
          const userData = await mapUserData(userToken);
          setUserCookie(userData);
          setUser(userData);
        } else {
          removeUserCookie();
          setUser();
        }
      });

    const userFromCookie = getUserFromCookie();
    if (!userFromCookie) {
      return;
    }
    setUser(userFromCookie);
    return () => cancelAuthListener;
  }, []);

  return { user, logout };
};

export { useUser };

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript reactjs firebase firebase-authentication


    【解决方案1】:

    您只能在服务器环境中使用 admin sdk(例如在 Firebase Functions 或其他服务器中) - 您不能在使用 React 的客户端环境中使用它。从概念上讲,它的工作方式是:

    1. 用户在您的客户端应用中输入用户名和密码
    2. 客户端应用程序将用户名和密码发送到您的服务器
    3. 服务器检查用户名和密码,如果正确,则使用管理 SDK 创建自定义令牌并将其发送回客户端应用
    4. 客户端应用使用该自定义令牌登录 Firebase

    所以它看起来像这样(注意 - 我在这里不处理任何错误,但你会想要):

    // client.js
    const sendToServer = (username, password) => {
      // Step 1 - client sends the username/password to the cloud function
      return axios.post(`${myCloudFunctionUrl}/login`, {
        username,
        password
      }).then((response) => {
        // Step 5 - the client logs the user in with the custom token
        return firebase.auth().signInWithCustomToken(response.data.token)
      }).then(() => {
        // Step 6 - the user is now logged in and redirected to the dashboard
        router.push("/dashboard")
      })
    }
    
    // server.js (using Firebase Functions, but use whatever back end you want)
    exports.login = functions.https.onRequest((req, res) => {
      const {username, password} = req.body
      // Step 2 - function verifies the username and password and gets the user's uid for the custom token
      return verifyUserInDatabase(username, password).then((uid) => {
        // Step 3 - the server creates a custom token
        return admin.auth().createCustomToken(uid)
      }).then((token) => {
        // Step 4 - the server sends the token back in its response
        res.json({ token })
      })
    })
    
    

    【讨论】:

      猜你喜欢
      • 2021-11-14
      • 1970-01-01
      • 2019-10-25
      • 1970-01-01
      • 1970-01-01
      • 2016-09-21
      • 2021-10-22
      • 2018-09-18
      • 2018-12-19
      相关资源
      最近更新 更多