首页 > 解决方案 > Firebase 读/写不符合安全规则

问题描述

我正在努力理解 Firebase 中的安全规则

我一直在使用标准的开发规则:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

我的应用程序读/写成功。我已经保护了页面,然后一旦用户登录,我就会进行各种调用以提取数据。我从 api 网关端点调用我的 lambda 函数,并在 lambda 内部我let readData = firebaseApp.database().ref(users/${userID}/data) 曾经在那里

readData.on('value', (snapshot) => {
    if (snapshot.exists()) {
        const data = snapshot.val()
        const myData = Object.keys(data).map((key) => {
            return data[key]
        })
        callback(null, {
            body: JSON.stringify(myData),
            headers: {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*',
            },
            statusCode: 200,
        })
    } else {
        callback(null, {
            body: JSON.stringify([]),
            headers: {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*',
            },
            statusCode: 200,
        })
    }
})

我将安全规则更新为

{
  "rules": {
    "users": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
      }
    }
  }
}

它完全失败并且 lambda 超时。我已经进入规则和模拟器,进入/users/aisofnasfoi(随机 id),然后打开身份验证,选择google作为提供者并输入 id。这行得通。

所以我想知道在我的代码中我还需要做什么才能通过这个经过身份验证的请求发送?

添加了额外的代码:所以我从 localStorage 解析用户,如果有,如果没有,我将它们添加到那里,这确保我知道他们已经登录

 const [newUser, setNewUser] = useState(JSON.parse(localStorage.getItem('authUser')))

useEffect(() => {
    firebaseApp.auth().onAuthStateChanged((user) => {
        if (user) {
            localStorage.setItem('authUser', JSON.stringify(user))
            setLoaded(true)
        } else {
            localStorage.removeItem('authUser')
            setLoaded(true)
            console.log(user, 'USER NOT LOGGED IN')
        }
    })

进一步的代码:

firebaseApp.auth().onAuthStateChanged((user) => {
            if (user) {
                localStorage.setItem('authUser', JSON.stringify(user))
                console.log(user, 'user') // this console logs the user object and uid lives in there with the value of: `2BnDBSvIhwfoYWKIwGH20rUzyKv1`

然后将其传递给我的函数:

useEffect(() => {
    if (user.isLoggedIn) {
        fetchData(user.details.uid)
    }
}, [user.isLoggedIn])

这个函数在这里定义:export const fetchData = (id) => ({ type: 'GET_USER_DATA', id: id })

反过来,一个 redux-observable 正在这里监听它,它调用了这个端点。当安全规则被关闭时,它总是为正确的登录用户获取正确的数据。由于将它们打开得更严格,我得到了超时:

https://API_GATE_WAY_ENDPOINT/data?userId=${action.id}(与上述相同的 id)

标签: javascriptfirebasefirebase-realtime-databasefirebase-authenticationfirebase-security

解决方案


推荐阅读