Search code examples
javascriptfirebasegoogle-cloud-platformgoogle-cloud-storagefirebase-security

Uploading a file to firebase storage returns 403 error despite changing database rules


I am creating a basic web page using HTML and JS to upload gifs into my firebase storage.

Here is my code:

<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title>Upload gifs</title>
  </head>
  <body>
    <progress value="0" max="100" id="uploader">0%</progress>
    <input type="file" valu="upload" id="fileButton"></input>

  </body>
    <script src="https://www.gstatic.com/firebasejs/7.7.0/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.7.0/firebase-storage.js"></script>

    <script>
        var firebaseConfig = {
          apiKey: "",
          authDomain: "",
          databaseURL: "",
          projectId: "",
          storageBucket: "",
          messagingSenderId: "",
          appId: "",
          measurementId: ""
        };
    firebase.initializeApp(firebaseConfig);
    console.log(firebase);

    var uploader = document.getElementById('uploader');
    var fileButton = document.getElementById('fileButton');

    fileButton.addEventListener('change', function(e){
      var file = e.target.files[0];

      var storageRef = firebase.storage().ref('gifs/' + "123");

      storageRef.put(file);

      task.on('state_changed', 
        function progress(snapshot) {
            var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            uploader.value = percentage;
        }
        ,
        function error(err) {

        }

      )
  })

    </script>
</html>

My rules for my firebase db are:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {

    match /{document=**} {
      allow read, write: if true;
    }
  }
}

Despite this when I run the code, it returns a 403 error saying its forbidden. I am not sure why as the rules have been changed to allow access to the database but I still have the issue. Will be grateful for any help.


Solution

  • You are mixing up the security rules of Cloud Firestore, one of the database services offered by Firebase, with the rules for Cloud Storage.

    You will find the documentation for Cloud Storage security rules here: https://firebase.google.com/docs/storage/security

    In your case, since it seems from your question that you want to allow anyone to read and write, you would write your Cloud Storage rules as follows:

    service firebase.storage {
      match /b/{bucket}/o {
        match /{allPaths=**} {
          allow read, write;
        }
      }
    }