Firebase读/写不适用于安全规则

时间:2020-05-18 07:17:20

标签: javascript firebase firebase-realtime-database firebase-authentication firebase-security

我正在努力了解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。这可行。

所以我想知道我还需要在代码中执行哪些操作才能通过此经过身份验证的请求?

添加了额外的代码: 所以我从那里的本地存储解析用户,如果没有,我在那里添加他们 这样可以确保我知道他们已登录

 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相同)

0 个答案:

没有答案