代码之家  ›  专栏  ›  技术社区  ›  Guy

Firebase auth with NodeJS:获取发出请求的客户端的UID

  •  0
  • Guy  · 技术社区  · 6 年前

    我用NodeJS和Firebase的 Realtime Database .

    {
      "rules": {
        ".read": "auth.uid === 'ADMIN_UID'",
        ".write": "auth.uid === 'ADMIN_UID'"
      }
    }
    

    当NodeJS Express服务器初始化时,我使用管理员凭据登录。

    在web应用程序中,我使用Firebase的“使用facebook登录”选项:

    const provider = new firebase.auth.FacebookAuthProvider();
    
    provider.setCustomParameters({
        display: "popup",
    });
    
    firebase
        .auth()
        .signInWithPopup(provider)
    

    现在,我试图从Web应用程序中提取发出请求的用户的用户Id(uid)。当我运行以下行时:

    const user = firebase.auth().currentUser;
    

    我得到的是管理员用户而不是发出请求的用户。我想这是意料之中的。我的问题是如何在不显式发送的情况下获取UserId以避免安全问题?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Guy    6 年前

    Firebase Admin SDK .

    如中所述 this 导游,你需要:

    1. 为您的服务帐户生成私钥

      • 点击 生成新私钥 ,然后单击确认 生成密钥 .
      • 安全地存储包含密钥的JSON文件。

    添加到.bashrc或.zshrc:

     export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
    

    admin.initializeApp({
      credential: admin.credential.applicationDefault(),
      databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
    });
    

    const token = await firebase.auth().currentUser.getIdToken()
    
    fetch(url, {
       method: "POST",
       headers: {
          "Content-Type": "application/json",
          Authorization: token
       },
       body: ...
     });
    

    在服务器中解密令牌并获取UID:

      return admin
            .auth()
            .verifyIdToken(token)
            .then(function(decodedToken) {
                var uid = decodedToken.uid;
                console.log("uid ->", uid);
                return uid;
            })
            .catch(function(error) {
                console.log("error ->", error);
    
                // Handle error
            });
    

    就这样。显然,通过自己的NodeJS域与Firebase协作被称为“使用自定义后端”。这意味着它们的默认用法是没有NodeJS或其他后端中间人。

        2
  •  0
  •   Flignats    6 年前

    通常在firebase中,您可以包括访问 context 用户ID是可用的。

    context.params.userId