Firebase Storage: User not permitted to access object despite public rules - android

I am new to Firebase storage. I made a simple app that should download a file from Firebase.
The download fails every time with the following error:
StorageException: StorageException has occurred.
User does not have permission to access this object.
Code: -13021 HttpResult: 403
These are my rules on Firebase:
service firebase.storage {
match /b/***.appspot.com/o {
match /{allPaths=**} {
allow read, write: if true;
}
}
}
I already also tried to enable anonymous authentification, but this doesn't change anything despite the login is successful.
EDIT: This is my java code:
FirebaseAuth mAuth;
mAuth = FirebaseAuth.getInstance();
mAuth.signInAnonymously().addOnCompleteListener((Activity) context, new OnCompleteListener<AuthResult>() {...}
FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
//Create a storage reference from our app
storageRef = firebaseStorage.getReference();
contentDir = new File(context.getFilesDir().getAbsolutePath() + "\\content\\testfile.txt");
storageRef.getFile(contentDir).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {...}

Update:
Downloading files from the storage root is either not supported or is not covered by the default security rule. (Maybe match /{allPaths=**} doesn't include root?) Move the file to some location other than the root:
FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
storageRef = firebaseStorage.getReference("anyPath");
If for testing you want to allow public access to you storage bucket, use these rules, copied from the Storage Guide. The rule posted by j_h_o_m_o is safer, limiting access to signed-in users:
// Anyone can read or write to the bucket, even non-users of your app.
service firebase.storage {
match /b/***.appspot.com/o {
match /{allPaths=**} {
allow read, write;
}
}
}
Also check that your bucket name matches what you see in the Firebase Console. For example, if the Storage Files tab shows gs://project-12345.appspot.com, your rule would start:
match /b/project-12345.appspot.com/o {

NOTE: this will let anyone access your storage authenticated or not
try changing your rules to the storage to this
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth == null;
}
}
}

Related

Loading Image from Firebase Storage using Kotlin

`
Hello I'm trying to load some images from Firebase Storage using downloadUrl but it always crashes and I don't know why I already set up rules in the storage but it still doesn't work
I added these dependencies
implementation 'com.google.firebase:firebase-storage-ktx'
implementation platform('com.google.firebase:firebase-bom:31.0.2')
My code is this:
`var storageRef = Firebase.storage.reference.child("post/$uId/$fileName.png") //I want to load image from a certain user
var imageUri:String?=null
storageRef.downloadUrl.addOnSuccessListener { Uri->
imageUri=Uri.toString()
}
-.addOnFailureListener {
Toast.makeText(this#UploadActivity, it.message, Toast.LENGTH_SHORT).show()
}`
Basically when debugging it doesn't enter addOnSuccessListener nor addOnfailureLister and imageUri remains null even though I can see that downloadUrl has translated the gs://... to https://firebase...
I also added these rules indise my firebase Storage
`rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
`
The reason is that it may take time to fetch the Image from Firebase storage and before you get the Image from firebase storage you try to load the Image in ImageView and the app crashes because the Uri is still null.
Try
Firebase.storage.reference.child("post/$uId/$fileName.png").
downloadUrl.addOnSuccessListener { Uri->
Glide.with(YOUR_ACTIVITY_CONTEXT).
load(Uri.toString()).
into(YOUR_IMAGE_VIEW)
}
-.addOnFailureListener {
Toast.makeText(this#UploadActivity, it.message, Toast.LENGTH_SHORT).show()
}`
For detailed knowledge of Glide Library here is the link

Flutter - FirebaseException ([firebase_storage/unknown] An unknown error occurred, please check the server response.)

I have been building an app for IOS and Android using flutter which uses firebase storage to upload files to cloud storage.I have multiple page from which i can upload files(eg:Theres a page to upload images,a seperate page tp upload pdf) but on certain pages, it throws this Exception:
Note: Page here refers to different Activity like in Android
FirebaseException ([firebase_storage/unknown] An unknown error occurred, please check the server response.)
I use same code to upload files on every page,but it throws this Exception.
When i click the upload button multiple times it will upload Sometime and most of times it fails with this Exception.
I have tried many solution including changing the security rules and adding firebase-storage#system.gserviceaccount.com as principle.
Iam using IOS Simulator for testing on IOS and physical device for android.Incase pf physical device for adroid i havnt faced any issue yet,but for simulator it throws this Exception
Here's the code i use to upload files:
uploadrepfile() async {
print("uploadiong");
final path = '${widget.uid}/Records/';
final file = File(pickedfile!.path!);
final pdfref = FirebaseStorage.instance.ref().child(path);
setState(() {
uploadTask = pdfref.putFile(file);
});
//final snapshot = await uploadTask!.whenComplete(() {});
final snapshot = await uploadTask!.whenComplete(() {});
final url = await snapshot.ref.getDownloadURL();
print(url);
FirebaseFirestore.instance
.collection("Medicalrecords")
.add({"url": url, "time": DateTime.now()});
setState(() {
uploadTask = null;
});
}
Here's my security rules:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if true;
}
match /users/{userId}/{allPaths=**} {
allow read: if true;
allow write: if request.auth.uid == userId;
}
}
}
Any help is Appreciated

Flutter Fire - [Firebase Storage] W/NetworkRequest( 5624): no auth token for request

My flutter app has a download feature that displays pdf from firebase storage and a download button to download the file. The view pdf function is working fine. However, the download pdf throws an exception
W/StorageUtil( 5624): no auth token for request
D/EGL_emulation( 5624): app_time_stats: avg=107.69ms min=6.46ms max=1118.11ms count=13
W/StorageUtil( 5624): Error getting App Check token; using placeholder token instead. Error: com.google.firebase.FirebaseException: Too many attempts.
E/StorageException( 5624): An unknown error occurred, please check the HTTP result code and inner exception for server response.
E/StorageException( 5624): User does not have permission to access this object.
E/StorageException( 5624): Code: -13021 HttpResult: 403
E/StorageException( 5624): { "error": { "code": 403, "message": "Permission denied." }}
Details about the app:-
The App does not have authentication (Feature not required so far)
The storage rules in firebase storage is open to all users.
match /documents/{docId}{allow read,write;}
App check not enabled or enforced. All requests are allowed to the storage bucket so far.
The sample code that I am trying to download the file is
Future<void> downloadFile(String downloadUrl, String filename) async {
Directory appDocDir = await getApplicationDocumentsDirectory();
File downloadToFile = File('${appDocDir.path}/$filename');
try {
var url = await firebase_storage.FirebaseStorage.instance
.ref('documents/$filename')
.storage
.ref();
await url.writeToFile(downloadToFile);
} on firebase_core.FirebaseException catch (e) {
print('Exception' + e);
}
}
I have updated all the packages & dependencies but in vain. I am sure that I am missing something. A helping hand will be greatly appreciated.
Try:
final isRef = await firebase_storage.FirebaseStorage.instance
.ref().child("'documents/$filename'");
Directory appDocDir = await getApplicationDocumentsDirectory();
File downloadToFile = File('${appDocDir.path}/$filename');
final downloadTask = isRef.writeToFile(downloadToFile);

IllegalArgumentException: Firebase Storage URLs must point to an object in your Storage Bucket when trying to link a cloudinary URL to firebase

I am using Cloudiary service in order to decrease the size of an uploaded video. I am getting back a URL of a picture (which I assume is the first frame of the video) back as a response. When trying to load the video from firebase I am for some reason getting a URL and not a URI. here is my method -
private void loadVideoUri(String storageUri) {
if (StringUtils.isBlank(storageUri)) {
return;
}
// load firebase storage
Task<Uri> downloadUrlTask = FirebaseStorage.getInstance().getReferenceFromUrl(storageUri).getDownloadUrl(); // -> crash happends here
if (getContext() instanceof Activity) {
downloadUrlTask.addOnCompleteListener((Activity) getContext(), mOnDownloadUrlCompleted);
} else {
downloadUrlTask.addOnCompleteListener(mOnDownloadUrlCompleted);
}
}
here is the full error -
java.lang.IllegalArgumentException: Firebase Storage URLs must point to an object in your Storage Bucket. Please obtain a URL using the Firebase Console or getDownloadUrl().
at com.google.firebase.storage.internal.Util.normalize(com.google.firebase:firebase-storage##16.0.5:134)
at com.google.firebase.storage.FirebaseStorage.getReferenceFromUrl(com.google.firebase:firebase-storage##16.0.5:281)
at com.onemdtalent.app.ui.views.mdview.FirebasePlayerView.loadVideoUri(FirebasePlayerView.java:156)

Amazon AWS S3 file upload. How to set file permissions?

I'm uploading a file using Amazon's AWS SDK (S3), and everything is working fine. Below is my code:
final AWSCredentials credentials = new AWSCredentials() {
#Override
public String getAWSAccessKeyId() {
return "...myAccessKey...";
}
#Override
public String getAWSSecretKey() {
return "...mySecretKey...";
}
};
final StaticCredentialsProvider credentialsProvider = new StaticCredentialsProvider(credentials);
final TransferManager transferManager = new TransferManager(credentialsProvider);
final Upload upload = transferManager.upload(Config.AWS_IMAGE_BUCKET, "images/" + file.getName(), file);
Problem is, whenever I upload something like this, the permissions are not set to public, so I can't use them in my app.
How can I set the file permissions from my code so that it's viewable by public?
Thanks!
You need to provide a PutObjectRequest with the ACLs you want when you call upload.
Choose appropriate ACL policy when you put file in to the bucket.
It can be one of the following option:
1) ACL_AUTHENTICATED_READ
Allow read access to authenticated users.
2) ACL_PRIVATE
Allows only private access to the file.
3) ACL_PUBLIC_READ.
Allows public read access to the file.
4) ACL_PUBLIC_READ_WRITE
Allows public read write access to the file when you write files onto the bucket.

Categories

Resources