简体   繁体   English

Firebase:权限被拒绝 - 而setValue()

[英]Firebase : Permission denied - while setValue()

I am trying to build a chat application using firebase. 我正在尝试使用firebase构建聊天应用程序。

The structure for message table : 消息表的结构:

message -
   $message_id 
    - $message_push_id 
      - message {
        sender : 3, 
        receiver : 58,
        token : token_of_sender,
        message : hi 
        ....}

message_id here is generated using the sender and receiver ids "3_58" 这里使用发送方和接收方ID “3_58”生成message_id

I am using push to save messages into firebase. 我正在使用push将消息保存到firebase中。

{
    "rules": {
        ".read": true,
         "message":
        {
          "$messageid": {
            "$messagepushid":
            {
              ".read": true,
              ".write": "auth != null  && !data.exists()",
              ".indexOn": ["token", "userid", "receiverid", "sent_time"],
              ".validate": "auth.token == newData.child('token').val() && newData.hasChildren(['token', 'userid', 'receiverid', 'text'])"
            }
          }
        }
    }
}

I have already generated token using custom token generator : 我已经使用自定义令牌生成器生成令牌:

Firebase firebase = getFirebase();
Map<String, Object> authPayload = new HashMap<String, Object>();
authPayload.put("uid", user.getUserid());
authPayload.put("token", user.getToken());
TokenGenerator tokenGenerator = new TokenGenerator(Constants.FIREBASE_KEY);
TokenOptions tokenOptions = new TokenOptions();
tokenOptions.setAdmin(false);
final String firebaseToken = tokenGenerator.createToken(authPayload, tokenOptions);
firebase.authWithCustomToken(firebaseToken, new Firebase.AuthResultHandler() {
    @Override
    public void onAuthenticated(AuthData authData) {
        Log.d("Auth", "Success : " + authData.toString());
        Log.d("Auth", "Token : " + firebaseToken);
        SharedPrefs.setFirebaseUserToken(getActivity(), firebaseToken);
    }

    @Override
    public void onAuthenticationError(FirebaseError
    firebaseError) {
        firebaseError.toException().printStackTrace();
    }
});

I am trying to push a new message but I am getting error : 我试图推送一条新消息,但我收到错误:

RepoOperation﹕ setValue at /message/3_58/-Jy2We4cqLjuQNF6Oyhs failed: FirebaseError: Permission denied RepoOperation:setValue at / message / 3_58 / -Jy2We4cqLjuQNF6Oyhs失败:FirebaseError:权限被拒绝

I am unable to figure out where I am going wrong. 我无法弄清楚我哪里出错了。

This is the code to send chat : 这是发送聊天的代码:

mConversationReferenceFireBase = mFireBase.child("message").child(mConversationId);
    Chat conversation = new Chat( mToken, mUserId, mReceiverId, message );
    mConversationReferenceFireBase.push().setValue(conversation, new Firebase.CompletionListener() {
        @Override
        public void onComplete(FirebaseError firebaseError, Firebase firebase) {
            if (firebaseError != null) {
                Log.e("Conversation", firebaseError.toString());
            }
        }
    });

mConversationId = 3_58 mConversationId = 3_58

The token here is generated for a user. 此处的令牌是为用户生成的。 We have a separate server to maintain the user accounts. 我们有一个单独的服务器来维护用户帐户。 The token is being used to upload/ download any files, the firebase is used as Chat Server. 令牌用于上传/下载任何文件,firebase用作聊天服务器。

With the rules set to .read = true and .write = true; 规则设置为.read = true和.write = true; everything works, however when I am attempting to have an authentication performed, it results in the error mentioned above. 一切正常,但是当我尝试进行身份验证时,会导致上述错误。 I've tried using the token from token generator, to check if I may possibly be using the wrong token. 我已经尝试使用令牌生成器中的令牌来检查我是否可能使用了错误的令牌。

I am following this example to generate token for firebase auth : 我按照这个例子为firebase auth生成令牌:

https://www.firebase.com/docs/web/guide/login/custom.html https://www.firebase.com/docs/web/guide/login/custom.html

Since storing a firebase secret key is bad in terms of security, what other alternative can be followed to generate a token for authentication? 由于存储firebase密钥在安全性方面是不好的,因此可以采用其他替代方法来生成用于身份验证的令牌?

I was too stuck on this point and here's what helped me. 我太过坚持这一点,这就是帮助我的原因。

First things first, there are two types of users who can access database from firebase 首先,有两种类型的用户可以从firebase访问数据库

  1. Authorized 合法
  2. Non-authorized 非授权

By default it is set to non-authorized but then they do not have any permissions neither read nor write, so initially if you try to perform any operation you get the permission denied error. 默认情况下,它设置为未授权,但是它们没有任何读取或写入权限,因此,如果您尝试执行任何操作,则最初会收到权限被拒绝错误。

So basically one has to change the required permissions on the firebase console in-order to access the database. 因此,基本上必须更改firebase控制台上所需的权限才能访问数据库。

Complete answer here 在这里完成答案

Check the rule defined in your firebase account and also the simulator options. 检查您的firebase帐户中定义的规则以及模拟器选项。 Description is given below in a image. 下面在图像中给出描述。

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM