在 Cloud Firestore 规则中 request.auth.uid 似乎始终为 null

Gui*_*rio 7 firebase firebase-security firebase-authentication google-cloud-firestore

我一定在这里遗漏了一些非常基本的东西......但是每当我调用我的 Cloud Firestore 数据库并尝试制定任何类型的安全规则时,它们总是失败。

做类似的事情

    match /users/{userId} {
      allow create, read, update: if true;
    }
Run Code Online (Sandbox Code Playgroud)

有效,但它显然违背了这一点。但是,如果我进行任何类型的额外审查,例如所有文档中的首选示例,例如

    match /users/{userId} {
      allow create, read, update: if request.auth.uid != null;
    }
Run Code Online (Sandbox Code Playgroud)

它每次都失败。我是否在如何将客户端代码连接在一起时遗漏了一些明显的东西?

这是我的客户端代码,用于登录用户,然后调用数据库以获取用户。(请注意,在我的数据库中,用户的密钥是通过电子邮件,而不是 uid)

// this is a snippet from the code where I log the user in
firebase.auth().signInWithEmailAndPassword(email, FIREBASE_USER_PASSWORD)
            .then(user => {
            // the user comes back successfully logged in, 
            // I grab its uid and add it to a preparedUser object that I've been building, 
            // then pass this user to my getFirestoreUserObject function
                preparedUser.uid = user.uid;
                getFirestoreUserObject({dispatch, user: preparedUser, navigate});
            })
            
// then the getFirestoreUserObject function:
// note that all the code below works fine when there are no security rules in place

const getFirestoreUserObject = ({dispatch, user, navigate}) => {
    const {name, email, imageUrl} = user;
    // if I ask for currentUser here, I get back my logged in user
    const currentUser = firebase.auth().currentUser;

    // email is defined correctly here as the user's email
    firebase.firestore().collection('users').doc(`${email}`)
        .get() // the request fails here due to insufficient permissions
        .then(doc => {
            if (doc.exists) {
                const currentUser = doc.data();

                getUserFavorites({dispatch, currentUser, navigate});
            } else {
                createUserInFirestore({dispatch, user, navigate});
            }
        })
};
Run Code Online (Sandbox Code Playgroud)

有什么明显的东西我失踪了吗?如果我通过 登录用户firebase.auth(),然后在 call 之后立即登录,那firebase.firestore()不应该有经过身份验证的用户的上下文吗?如果没有,我如何将它传递给 firestore 调用?

谢谢!

Gui*_*rio 7

经过数周的搜索,firestore 和 auth 都独立工作但不一起工作......这是最简单的事情。

我使用的是 firebase 4.x,这是我开始我的项目时可用的最新版本。然后,当我开始添加身份验证规则时,有关如何执行数据库规则的最新发布的关于 firebase 的文档(我开始时甚至没有看过,但几个月后我准备实施它们时又回来了) ) 是使用 firebase 5.y 列出的。更新了我的 package.json、npm install,一切都神奇地工作了 :(

希望这可以帮助其他人...确保您至少使用第 5 版!

使用以下方法更新模拟器: npm install -g firebase-tools