User does not have permission to access this object . Firebase storage android
Asked Answered
C

15

75

I am new to firebase storage. Just so I could learn it, I made a simple app that has a button and an ImageView. When I click on the button, an image (from drawable) gets displayed on the ImageView. I have also written the code for uploading the image on Firebase, but the exception message of onAddFailureListener gives message User does not have permission to access this object. What should I do ?

package com.example.asad.save_photo;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageMetadata;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.io.ByteArrayOutputStream;
import java.io.File;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FirebaseStorage storage = FirebaseStorage.getInstance();

        StorageReference storageRef = storage.getReferenceFromUrl("gs://savephoto-a1cc3.appspot.com");

        final StorageReference mountainsRef = storageRef.child("asad");

        Button butt = (Button) findViewById(R.id.button);


        butt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ImageView imageView = (ImageView) findViewById(R.id.image);
                imageView.setImageResource(R.drawable.back2);
                //imageView.setImageResource(R.drawable.back2);

                imageView.setDrawingCacheEnabled(true);
                imageView.buildDrawingCache();
                Bitmap bitmap = imageView.getDrawingCache();


                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                final byte[] data = baos.toByteArray();

                UploadTask uploadTask = mountainsRef.putBytes(data);
                uploadTask.addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        // Handle unsuccessful uploads
                        showToast(exception.getMessage());
                    }
                });
                        uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
                        //Uri downloadUrl = taskSnapshot.getDownloadUrl();
                        showToast("success !!!!!");
                    }
                });


            }
        });

    }

    public void showToast(String s) {
        Toast.makeText(this,s,Toast.LENGTH_LONG).show();
    }
}

Here are my firebase storage rules

service firebase.storage {
  match /b/savephoto-a1cc3.appspot.com/o {
    allow read,write;
  }
}
Cambrel answered 30/7, 2016 at 7:21 Comment(6)
your OS version is 6.0 ? if yes then get runtime permission from #38142023Harvard
Nope. My OS version is 4.2Cambrel
Have you add permissions in manifest file?Harvard
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> This is the only one I have added. I am really new to it so please feel free to point out mistakesCambrel
<uses-permission android:name="android.permission.INTERNET" /> This one too.Cambrel
You need to change your security rules in firebase storage rulesKowloon
D
129

Update your security rules with match /{allPaths=**} to indicate that public read and write access is allowed on all paths:

service firebase.storage {
  match /b/savephoto-a1cc3.appspot.com/o {
    match /{allPaths=**} {
      // Allow access by all users
      allow read, write;
    }
  }
}

Various default rules are provides in the tabs of the Sample Rules section of the documentation.

Deduct answered 30/7, 2016 at 12:58 Comment(2)
where do you add this?Vague
@rosualin: At the Firebase Console for your projectDeduct
B
39

Change your storage rules in Firebase console

enter image description here

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth != null;
    }
  }
}
Bowden answered 7/10, 2017 at 10:37 Comment(2)
I have that exact setup and am still receiving that error.Acculturation
Worked for me after removing : if request.auth != nullFitzgerald
D
32

Follow these steps

  1. Go to "Storage"

  2. Select "Rules" tab and edit rules as per below:

if your application have authentication feature(login) then use this:

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

if your application does not have login feature(directly any user can access storage) then use this:

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write;
    }
  }
}
Downstream answered 10/11, 2020 at 15:31 Comment(0)
M
13

Go to storage -> Rules tab

add this

// Anyone can read or write to the bucket, even non-users of your app.
// Because it is shared with Google App Engine, this will also make
// files uploaded via GAE public.
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write;
    }
  }
}

enter image description here

Marybelle answered 2/7, 2018 at 5:13 Comment(0)
S
11

Just go to Storage - Rules. Enter the rule as following, replacing the bucket name with your own bucket name. You can find the bucket name by going to Storage - Files.

It should look something like this: myapplication-xxxx.appspot.com

That's all you need. You don't need to enable authentication, if you are doing it for testing purposes only. If you need authentication, you can add it later.

enter image description here

Stultz answered 12/8, 2018 at 19:59 Comment(1)
You literally helped me, my problem was that i copy this match from somewhere else and it didn't match my application name at all. After a while i have found your explanation and that's it, I own you a drink :) .Ischia
A
4

please go to your storage/rules folder in firebase and paste this following code.

 rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write;
    }
  }
}
Alagoas answered 14/6, 2021 at 18:22 Comment(0)
G
2

The issue is with your firebase storage rules. Change it to

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

Make sure the if request.auth != null

Granulation answered 25/8, 2020 at 6:52 Comment(0)
T
1

Allow write by only authenticated user, but read by all:

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

Tallboy answered 24/7, 2022 at 11:30 Comment(0)
S
0

These soloutions really did not solve my problem.

what have solved my problem are those lines:

in app module

implementation 'com.google.firebase:firebase-database:15.0.0'
implementation 'com.google.firebase:firebase-storage:15.0.0'
implementation 'com.google.firebase:firebase-auth:15.0.0'

and this code for uploading and getting a download link

private void uploadImageToFirebase(Bitmap bmp) {

    try {
        String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
                "/news";
        File dir = new File(file_path);
        if (!dir.exists())
            dir.mkdirs();
        File file = new File(dir, "sketchpad" + "_" + ".png");
        FileOutputStream fOut = new FileOutputStream(file);
        bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        fOut.flush();
        fOut.close();
        Log.i("SECONDACTIVITY", "ADDED SUCCESSFULLY");

        Uri file2 = Uri.fromFile(file);


        //Now Upload
        final StorageReference storageRef = FirebaseStorage.getInstance().getReference();
        StorageReference riversRef = storageRef.child(file.getName());
        UploadTask uploadTask;
        uploadTask = riversRef.putFile(file2);
        progressDialog.show();
        progressDialog.setCancelable(false);


        uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                progressDialog.incrementProgressBy((int) progress);
            }
        });
        uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                progressDialog.dismiss();
                Uri DownloadLink = taskSnapshot.getDownloadUrl();
                String imgUrl = DownloadLink.toString();
                FirebaseDatabase.getInstance().getReference().child("image_link").setValue(imgUrl);
            }
        });
        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                progressDialog.dismiss();
            }
        });


    } catch (IOException e) {
        e.printStackTrace();
    }


}
Striped answered 19/2, 2019 at 22:53 Comment(0)
S
0
service firebase.storage {
  match /b/fir-upload-a2fa6.appspot.com/o {
    match /{allPaths=**} {
      // Allow access by all users
      allow read, write;
    }
  }
}
Savdeep answered 5/4, 2019 at 6:32 Comment(1)
Please, can you extend your answer with more detailed explanation? This will be very useful for understanding. Thank you!Bianca
S
0

Firebase Storage Error (solved) 1. Go to firebase console under the project you are working on 2. Under storage on the firebase console and under rules edit the service firebase.storage to.

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write;
    }
  }
}
Serial answered 20/9, 2020 at 14:47 Comment(0)
M
0

I am adding this answer hoping it will help someone, in Firebase:

  1. go to "Storage"

  2. Select "Rules" tab and edit rules as per below:

    service firebase.storage {
       match /b/{bucket}/o {
         match /{allPaths=**} {
           // Allow access by all users
           allow read, write: if request.auth != null;
         }
       }
     }
    

Note: make sure you have it exactly as above, do not replace {bucket} for your project name.

Musicianship answered 30/10, 2020 at 7:33 Comment(0)
X
0

Firebase Storage Error (solved) 1. Go to firebase console under the project you are working on 2. Under storage on the firebase console and under rules edit the service firebase.storage to.

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

Note: If have't solve this problem then check your firebase plan expires.

Xyster answered 18/2, 2021 at 12:27 Comment(0)
R
0

I have just changed the date like before it was timestamp.date(2023, 3, 27) to timestamp.date(2023, 6, 27);

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if
          request.time < timestamp.date(2023, 6, 27);
    }
  }
}
Ramin answered 1/4, 2023 at 14:14 Comment(0)
R
0

J'ai assemblé les règles depuis la documentation officielle et sans utiliser request.auth le problème de permission refusé de firebase storage a été réglé

rules_version = '2';

// Craft rules based on data in your Firestore database
// allow write: if firestore.get(
//    /databases/(default)/documents/users/$(request.auth.uid)).data.isAdmin;
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read; 
      allow write: if request.resource.size < 2 * 1024 * 1024
                   && request.resource.contentType.matches('image/.*');
    }
  }
}
Reede answered 18/7 at 10:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.