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

AndroidFirebaseFirebase Storage

Android Problem Overview


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;
  }
}

Android Solutions


Solution 1 - Android

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.

Solution 2 - Android

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;
    }
  }
}

Solution 3 - Android

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

Solution 4 - Android

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

Solution 5 - Android

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;
    }
  }
}

Solution 6 - Android

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;
    }
  }
}

Solution 7 - Android

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();
    }


}

Solution 8 - Android

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

Solution 9 - Android

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

Solution 10 - Android

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;
    }
  }
}

Solution 11 - Android

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.

Solution 12 - Android

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionashayView Question on Stackoverflow
Solution 1 - AndroidBob SnyderView Answer on Stackoverflow
Solution 2 - AndroidGhanshyam NaymaView Answer on Stackoverflow
Solution 3 - AndroidKishan SolankiView Answer on Stackoverflow
Solution 4 - Androidlive-loveView Answer on Stackoverflow
Solution 5 - AndroidMukul RaghavView Answer on Stackoverflow
Solution 6 - AndroidHannanView Answer on Stackoverflow
Solution 7 - AndroidBrigth LigthView Answer on Stackoverflow
Solution 8 - AndroidVivek SoniView Answer on Stackoverflow
Solution 9 - AndroidWorldbossView Answer on Stackoverflow
Solution 10 - AndroidcrispengariView Answer on Stackoverflow
Solution 11 - AndroidHaroldSerView Answer on Stackoverflow
Solution 12 - AndroidMehedi HasanView Answer on Stackoverflow