VueJS+VueFire结合Firebase实时数据库带认证存数据遇权限拒绝
解决VueFire + Firebase实时数据库的权限拒绝问题
嘿,这个权限拒绝的问题我太熟了!咱们一步步来搞定它~
问题根源分析
你遇到的PERMISSION_DENIED错误主要有两个原因:
- 权限规则未覆盖目标路径:你的Firebase规则只配置了
users/$uid的读写权限,但你实际操作的是notes路径,规则里完全没提到这个路径,所以Firebase直接拒绝了你的写入请求。 - 代码中的路径不匹配:你在用户登录后绑定的是
notes/${user.uid}这个用户专属节点,但addNote方法里却直接往根节点notes下push数据,既不符合规则的预期,也和你绑定的数据源不一致。
解决方案
1. 更新Firebase实时数据库规则
把notes路径的权限也加上,确保每个用户只能读写自己uid下的notes节点:
{ "rules": { "users": { "$uid": { ".read": "$uid === auth.uid", ".write": "$uid === auth.uid" } }, "notes": { "$uid": { ".read": "$uid === auth.uid", ".write": "$uid === auth.uid" } } } }
2. 调整VueJS代码(addnote.vue)
修改代码中的数据引用和绑定逻辑,确保写入的是用户专属的notes节点,同时修复Google登录的小问题:
<script> import Firebase from 'firebase' let config = { apiKey: '[...]', authDomain: '[...].firebaseapp.com', databaseURL: 'https://[...].firebaseio.com', projectId: '[...]', storageBucket: '', messagingSenderId: '[...]' } let app = Firebase.initializeApp(config) let db = app.database() export default { name: 'app', beforeCreate: function () { Firebase.auth().onAuthStateChanged((user) => { if (user) { this.user = user // 动态绑定当前用户的notes列表 this.$bindAsArray('notes', db.ref(`notes/${user.uid}`)) // 保存当前用户的notes引用到实例中 this.userNotesRef = db.ref(`notes/${user.uid}`) } else { // 用户登出时清空数据和引用 this.user = null this.userNotesRef = null this.notes = [] } }) }, data () { return { user: null, userNotesRef: null, newNote: { title: '', time: '', note: '' }, notes: [] } }, methods: { addNote: function () { // 确保用户已登录且引用存在时再写入 if (this.userNotesRef) { this.userNotesRef.push(this.newNote) // 清空输入框 this.newNote.title = '' this.newNote.time = '' this.newNote.note = '' } }, signInWithGoogle: function () { const provider = new Firebase.auth.GoogleAuthProvider() Firebase.auth().signInWithRedirect(provider) // 由于是跳转登录,需要用getRedirectResult获取用户信息 Firebase.auth().getRedirectResult().then((result) => { if (result.user) { this.user = result.user } }).catch(error => console.log(error)) } } } </script>
关键修改点说明
- 移除了全局的
notesRef,改为在用户登录后创建userNotesRef,指向notes/${user.uid},确保写入的是用户自己的专属节点,匹配权限规则。 - 去掉了静态的
firebase选项绑定,改为在onAuthStateChanged回调里动态绑定,避免用户未登录时触发不必要的权限请求。 - 修复了Google登录的逻辑:
signInWithRedirect不会直接返回用户结果,必须通过getRedirectResult在页面刷新后获取用户信息。 - 在
addNote方法里增加了判断,防止用户未登录时执行写入操作。
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

