You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase登录成功后用户无法访问自身数据的解决求助

解决Firebase实时数据库登录后无法读取自身数据的权限问题

我设置了Firebase实时数据库规则,希望用户登录后能访问自己的用户数据,但用户登录成功后却收到「客户端无所需权限访问目标数据」的提示。以下是我的数据库规则和尝试代码:

当前数据库规则

{
  /* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
 
  "rules": {
    "users": {
      "$uid": {
        ".read": "auth.id === $uid",
        ".write": "auth.id === $uid"
      }
    }
  } 
}

尝试的登录读取代码

//my web app's Firebase configuration
var firebaseConfig = {
      // my configurations
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Initialize variables
const auth = firebase.auth()
const database = firebase.database()

// Set up our login function
function login () {
  // Get all our input fields
  email = document.getElementById('email').value
  password = document.getElementById('password').value

  // Validate input fields
  if (validate_email(email) == false || validate_password(password) == false) {
    alert('Email or Password is Outta Line!!')
    return
    // Don't continue running the code
  }

  var database_ref = database.ref()
  auth.signInWithEmailAndPassword(email, password)
  .then(function() {
    // Declare user variable
    var user = auth.currentUser
    
    // Create User data
    var user_data = {
      last_login : Date.now()
    }
    
    // Push to Firebase Database
    database_ref.child('users/' + user.uid).update(user_data)
    
    const usersRef = database.ref('users');
    const userRef = usersRef.child(user.uid);
        
        
    // Add this user to Firebase Database
        //var database_ref = database.ref()
    
    userRef.once('value')
      .then(snapshot => {
        const userData = snapshot.val();
        alert(userData); // Access the retrieved user data
      })
      .catch(error => {
        alert(error);
      });
    
    // DOne
    alert('User Logged In!! && verified ' + user.emailVerified + " usernameIs "+ JSON.stringify(user.uid))

  })
  .catch(function(error) {
    // Firebase will use this to alert of its errors
    var error_code = error.code
    var error_message = error.message

    alert(error_message)
  })
}

问题原因及解决方法

核心错误出在数据库安全规则的字段使用上:Firebase实时数据库安全规则中,当前登录用户的UID字段是auth.uid,而非你写的auth.id。字段不匹配导致权限验证失败,即使用户登录成功也无法读取数据。

修正后的数据库规则如下:

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

替换规则后,原有代码逻辑无需修改即可正常工作:用户登录后通过user.uid定位到自己的节点,规则会验证auth.uid与节点的$uid是否一致,匹配则允许读写操作。

内容的提问来源于stack exchange,提问作者Abednego Nasila

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 08:13:34