【问题标题】:Android Firebase Database Error: Permission deniedAndroid Firebase 数据库错误:权限被拒绝
【发布时间】:2017-04-17 23:18:42
【问题描述】:

我正在开发一个需要用户电子邮件和密码验证的 android 项目。详细信息存储在 firebase 数据库中。每当我尝试使用电子邮件和密码再次登录时,都会出现问题。在我的 logcat 中,错误消息是:

W/SyncTree: Listen at / failed: DatabaseError: Permission denied

看看我下面的代码:

public class LoginUser extends AppCompatActivity {

private RelativeLayout relativeLayout;

private EditText et_email, et_password;
private Button loginBtn;

private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener authStateListener;
private DatabaseReference databaseReference;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login_user);

    mAuth = FirebaseAuth.getInstance();
    databaseReference = FirebaseDatabase.getInstance().getReference();
    databaseReference.keepSynced(true);

    relativeLayout = (RelativeLayout) findViewById(R.id.activity_login_user);

    et_email = (EditText) findViewById(R.id.emailField);
    et_password = (EditText) findViewById(R.id.pwdField);
    loginBtn = (Button) findViewById(R.id.loginBtn);

    loginBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            initLogin();
        }
    });

    authStateListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            if (firebaseAuth.getCurrentUser() != null){
                initLogin();
            }
            else {
                startActivity(new Intent(LoginUser.this,RegisterFireBase.class));
            }
        }
    };

}

@Override
protected void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(authStateListener);
}

@Override
protected void onStop() {
    super.onStop();
    if (mAuth != null){
        mAuth.removeAuthStateListener(authStateListener);
    }
}

private void initLogin() {

    String email = et_email.getText().toString().trim();
    String pass = et_password.getText().toString().trim();

    if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(pass)){
        mAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {

                checkForUser();

            }
        });
    }
    else {
        Toast.makeText(this, "Some fields are empty", Toast.LENGTH_SHORT).show();
    }

}

private void checkForUser() {

    final String userId = mAuth.getCurrentUser().getUid();
    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.hasChild(userId)){

                Intent loginIntent =  new Intent(LoginUser.this, FireProfile.class);
                loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(loginIntent);

                Snackbar.make(relativeLayout,"Log In Successful",Snackbar.LENGTH_LONG).show();

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

}

这可能是什么原因造成的?

【问题讨论】:

  • 除了错误消息已经说明的内容外,我们无话可说:您正在尝试读取您无权访问的数据。为了让我们更有帮助,请分享将触发此错误的 minimal JSON 和安全规则。

标签: android firebase firebase-realtime-database firebase-authentication


【解决方案1】:

可能的原因是:您没有数据库的读写权限。 启用读写访问:

转到 firebase 控制台并在您的数据库上启用读写操作。

Firebase 控制台 -> 数据库(开发)-> 规则

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

【讨论】:

  • 非常感谢。问题不在规则部分,但很高兴您做出回应。谢谢大家。
  • 您的安全规则被定义为公开的,因此任何人都可以窃取、修改或删除您数据库中的数据。使用该规则我收到上述警告。
【解决方案2】:

如果不需要,请不要将您的应用公开。 如谷歌文档所述,您可以在您的 firebase > database > rules 上执行这些规则

// These rules grant access to a node matching the authenticated
// user's ID from the Firebase auth token
{
  "rules": {
    "users": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
      }
    }
  }
}

或只允许经过身份验证的用户

// These rules require authentication
    {
      "rules": {
        ".read": "auth != null",
        ".write": "auth != null"
      }
    }

公开应用程序让任何人都可以编写和阅读您的应用程序...我认为任何应用程序都不应该那样使用它。

【讨论】:

    【解决方案3】:

    转到数据库控制台上的“规则”选项卡。如果您没有明确授予用户 .read 访问权限,则权限将被拒绝。

    Firebase 文档中的此链接非常好:

    https://firebase.google.com/docs/database/security/securing-data

    该页面上的这两个注释特别有趣:

    注意:默认情况下不允许访问。如果在路径或路径上方未指定 .write 或 .read 规则,则访问将被拒绝。

    注意:较浅的安全规则会覆盖较深路径的规则。子规则只能授予父节点已经声明的额外权限。他们不能撤销读取或写入权限。

    查看权限被拒绝的节点并使用“规则”选项卡上的模拟器来测试不同用户安全上下文(未验证、已验证等)的规则

    【讨论】:

      【解决方案4】:

      对 firebase 数据库进行一些更改。

      1. 转到 firebase -> 数据库 -> 规则

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

      【讨论】:

      • 由于非最佳可读性、缺乏解释、需要适当的格式以及链接文本的混乱使用,这降低了它的帮助。
      • 我为你解决了一些问题。请edit 添加解释,并可能添加“2”。或删除“1.”。
      • @Yunnosch thnx 寻求帮助。
      【解决方案5】:

      请尝试更改您的 Firebase 规则,如下所示我之前遇到过这个问题。 我的问题出在数据库规则中:

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

      【讨论】:

      • 如果我使用这些规则,任何人都可以进行更改。
      【解决方案6】:

      问题是firebase数据库有两个同名项目,甚至没有启用项目的规则之一 所以在所有项目上查看一次

      【讨论】:

        【解决方案7】:

        转到 firebase 控制台并在您的数据库上启用读写操作。

        Firebase 控制台 -> 数据库(开发)-> 规则

        rules_version = '2';
        service firebase.storage {
          match /b/{bucket}/o {
            match /{allPaths=**} {
              allow read, write: if request.auth != null;
            }
          }
        }
        

        如果您使用的是旧版本,请添加以下规则,

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

        【讨论】:

          【解决方案8】:

          大多数答案只是建议让任何人都可以访问数据库来阅读和编辑。对于粗略的测试,这可能是可以接受的,但对于任何严重的测试肯定是不行的。

          Google Firebase 允许配置允许和拒绝访问。在此处阅读官方文档: https://firebase.google.com/docs/rules/basics#realtime-database
          (确保选择正确类型的 Firebase 数据库)

          对于任何需要身份验证的内容,您需要设置 Firebase 身份验证:https://firebase.google.com/docs/auth

          以下是一些基本示例:

          无访问权限(默认)

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

          仅限经过身份验证的用户

          {
            "rules": {
              ".read": "auth.uid != null",
              ".write": "auth.uid != null"
            }
          }
          

          公开读取,仅由所有者写入

          {
          // Allow anyone to read data, but only authenticated content owners can
          // make changes to their data
          
            "rules": {
              "some_path": {
                "$uid": {
                  ".read": true,
                  // or ".read": "auth.uid != null" for only authenticated users
                  ".write": "auth.uid == $uid"
                }
              }
            }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-09-25
            • 2019-11-15
            • 2018-03-27
            • 1970-01-01
            • 2020-10-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多