javascript - 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)
解决方案
推荐阅读
- .net - 如何显示 NuGet 包依赖项?
- ios - 无法使用 Core Data 和 Swift 在表格视图中正确保存和显示数据
- javascript - 用过滤器代替接头
- sql - 在表 Sql Server 中创建多个编号的行
- android - 在 kotlin 中使用 itext5 将表格添加到现有 PDF
- html - 在 NavBar 中间定位 Logo
- list - 在 SharePoint 列表表单中生成动态列表列字段
- javascript - YouTube Data API 搜索中的“items”元素在调用“/videos”时不返回任何内容
- nltk - 如何通过nltk python标记文本
- json - 在 Swift 中:如何解码这个 JSON(它有可变键)?