question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Firebase Realtime Database xxxx-xxxx-4458' has insecure rules - custom authentication

See original GitHub issue

I am only using Firebase Realtime database just to creating chat app. The user verification working separately on our own server and we are not using any firebase auth service for user verification. As Frank van Puffelen suggested few official docs. I am now generating JWT to authorize as per documentation but as we are not using any other services of firebase i am not sure how to authorized the real time database with generated JWT. I also asked same on Stackoverlfow but i am not getting much response there you can check SO link below.

StackOverFlow reference

The process:

Server generates JWT With PHP Firebase JWT

$Token = JWT::encode($request_data,$secret_Key,'HS512');

this token return back to app if user login successfully.

After successfully user login i call sign in with custom token i received from server with firebase

firebaseAuth = FirebaseAuth.getInstance();
       firebaseAuth.signInWithCustomToken(Session.getJWT())
    .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task)    {             
        if (task.isComplete()){
            Intent intent=new Intent(getActivity(),MainActivity.class);
            getActivity().startActivity(intent); 
            }           
        }   
    });

When user click chat button. Check if room already exist or not if not then create one for 2 users with their phone numbers like 9810012345-9810012346

DatabaseReference db = rebaseDatabase.getInstance().getReference();
      db.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.hasChild(RoomTitle)) {
                    RoomName(RoomTitle, true);
                }else {
                    RoomName(RoomTitle, false);
                }
            }
    
            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });

public void RoomName(String Name, boolean RoomExist) {
    button_SendMessage.setEnabled(true);
    if (!RoomExist) {
        Log.d(TAG, "Room Not Exist Creating One);
        RoomName.put(Name, "");
        FireBaseDatabase.updateChildren(RoomName);
    }

        // Launch Chat Screen

}

Then on chat screen i add items like linked question database structure

databaseReference = FirebaseDatabase.getInstance().getReference().child(Room_Name);

So creating room,allow reading writing message only created room, block access if room doesn’t belong to users. I need to set rules for Realtime Database and only app users can access their rooms not others even they are app users(Block others app users to sneak into others users rooms) Below is the sample of our Realtime Database structure for better understanding how our 2 user room look like. I am not sure there is much thing to do on app side, i feel it’s more database than app code question. #

Issue Analytics

  • State:closed
  • Created 10 months ago
  • Comments:14 (6 by maintainers)

github_iconTop GitHub Comments

3reactions
varun7952commented, Nov 24, 2022

@argzdev Thanks for your help. Now i can successfully use these realtime database rules.

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

The issue was sending all required parameters to firebase realtime database. Because i am creating JWT by using third party library and for this the guide i found here

These are the required params for the custom token

Custom Token Claims

alg | Algorithm | “RS256” iss | Issuer | Your project’s service account email address sub | Subject | Your project’s service account email address aud | Audience | “https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit” iat | Issued-at time | The current time, in seconds since the UNIX epoch exp | Expiration time | The time, in seconds since the UNIX epoch, at which the token expires. It can be a maximum of 3600 seconds later than the iat. Note: this only controls the time when the custom token itself expires. But once you sign a user in using signInWithCustomToken(), they will remain signed in into the device until their session is invalidated or the user signs out. uid |   | The unique identifier of the signed-in user must be a string, between 1-36 characters long claims (optional) |   | Optional custom claims to include in the Security Rules auth / request.auth variables

As firebase only support RS256 Algorithm, my earlier algorithm HS512 was not working for this. Also the method i used to decode was giving OpenSSL unable to verify data which resolved by this github issue

// Extract public key from private key
$res = openssl_get_privatekey($privateKey);
$details = openssl_pkey_get_details($res);
$publicKey = $details['key'];
$token = JWT::decode($jwt, new Key($publicKey, 'RS256'));

All i need to modified rules for more security with this and this link

1reaction
varun7952commented, Nov 22, 2022

@argzdev I will try both method and give you an update soon. Thanks for helping me out.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Firebase Realtime Database xxxx-xxxx-4458' has insecure rules
If you want to properly secure access based on the user identity, you can inform Firebase Authentication of the profile of the user...
Read more >
"OpenSSL unable to verify data..." #116 - firebase/php-jwt
Firebase Realtime Database xxxx-xxxx-4458 ' has insecure rules - custom authentication firebase/firebase-android-sdk#4336.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found