403 error on downloadUrl (Kotlin) in Firebase Storage - firebase

Getting this error:
E/StorageUtil: error getting token java.util.concurrent.ExecutionException: com.google.firebase.internal.api.FirebaseNoSignedInUserException: Please sign in before trying to get a token.
This too:
E/StorageException: StorageException has occurred.
The user does not have permission to access this object.
Code: -13021 HttpResult: 403
E/StorageException: { "error": { "code": 403, "message": "Permission denied." }}
java.io.IOException: { "error": { "code": 403, "message": "Permission denied." }}
When this code is hit in my android app:
val urlTask = uploadTask?.continueWithTask { task ->
if (!task.isSuccessful) {
Toast.makeText(context, "Upload to Cloud Failed!", Toast.LENGTH_SHORT).show()
task.exception?.let {
throw it
}
} imagesRef?.downloadUrl.....ERROR IS GENERATED HERE...
Started when I turned on email/password authorization and turned off the anonymous sign in, however, I turned the anonymous sign-in back on and make sure auth is not null before starting the upload.
val auth = Firebase.auth
val user = auth.currentUser
ALSO, IT SAVES THE UPLOADED IMAGES TO STORAGE NO PROBLEM...but won't download the Url.
Here are the rules in place for my Firebase Storage:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /images/{imageId} {
allow write: if request.auth != null;
allow read: if request.auth != null;
}
}
}
I have not been able to find an answer to why it will upload but not download the URL.

The problem in your code is present due to the fact that your user is not authenticated when you try to read the file from Cloud Storage. To be able to read a file, you should always make sure your use is authenticated in Firebase. That being said, please check the FirebaseUser object against nullity before performing Cloud Storage operations.

Related

Permission to use Firebase Cloud Storage has been refused. This operation could not be completed. When fetching a downloadURL, use firebase

I have such a code that publishes a picture to my online storage buckets properly.
I'd want to retrieve the picture's URL using another function so that I may display it on my page.
"error": {
"code": 403,
"message": "Permission denied. Could not perform this operation"
}
buddy this works great for me
service firebase.storage {
match /b/{bucket}/o {
match /images/{imageId} {
// Only allow uploads of any image file that's less than 5MB
allow write: if request.resource.size < 5 * 1024 * 1024
&& request.resource.contentType.matches('image/.*');
}
}
}

'permission denied' error with random getDownloadURL flutter/firebase

I'm writing an app which has user profiles in it. The user is allowed to take a photo or choose from their photo library.
Once the photo is taken, I use this function:
Future<String> uploadFile(File image, String directory, String imageName) async {
assert(image.existsSync());
StorageReference storageReference = FirebaseStorage.instance.ref().child('$directory/$imageName');
StorageUploadTask uploadTask = storageReference.putFile(image);
await uploadTask.onComplete;
var dowurl = await storageReference.getDownloadURL();
return dowurl.toString();
}
to upload the image to firebase. The image appears in the Firebase storage area fine, and the URL is generated, and added to the user's profile as I've defined in the database.
The rules of firebase are set as follows:
Database
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
Storage
rules_version = '2';
service firebase.storage {
match /b/myappname.com/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
which I believe should allow access for any user as long as they're authenticated (they are!)
I'm uploading the URLs generated by uploadFile() to the users profile, but about 1/6 of them gives a URL which, when accessed gives the following error:
{
"error": {
"code": 403,
"message": "Permission denied. Could not perform this operation"
}
}
I'm at a loss as to what is going on here, as the rest of the code works fine, and the 'choice' of file which causes the problem seems completely random.
The URLs generated have different token IDs at the end of each, but I'm not generating them - they're coming from the getDownloadURL() function. I'm keen to stress that the process is the same for each file, but for some reason, randomly, one of the generated URLs doesn't work.
Any help would be much appreciated.

(Flutter) Can't download images with Cloud Storage

I get this error :
E/StorageUtil(21342): error getting token java.util.concurrent.ExecutionException: com.google.firebase.internal.api.FirebaseNoSignedInUserException: Please sign in before trying to get a token.
W/NetworkRequest(21342): no auth token for request
When I execute this code from https://stackoverflow.com/a/50877590/9272698 (to get the download url from an image with Firestore Storage) :
Future _getImageUrl() async {
final ref = FirebaseStorage.instance.ref().child('lake');
var url = await ref.getDownloadURL();
return url;
}
This is not due to my firestore rules since, I enabled it to be public like this :
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
Moreover I don't think it is due to internet connection since I'm able to load fields from Firebase Cloud Database.
Do you have a solution? Thanks a lot
I managed to get my url images.
Here's how :
Add SAH-1 certification to your project firebase and upload new google-service file to your project
Make your users sign-in anonymously (and enable it in your firebase project) before calling .getDownloadUrl()

Firebase storage and Invalid HTTP method/URL pair

When I try to fetch a firebase storage file using ReactReader, I get the following error:
{
"error": {
"code": 400,
"message": "Invalid HTTP method/URL pair."
}
}
The code is making a request to https://firebasestorage.googleapis.com/v0/b/....
but that returns the error above.
Has anyone run into this issue?
I have got this problem, but no t for security reason, but when I would put a file in a subdir.
I was (with Postman) trying:
https://firebasestorage.googleapis.com/v0/b/*YOURBUCKET*.appspot.com/o/Test/test.pdf
And I got exactly this error ("message": "Invalid HTTP method/URL pair.").
The problem was the encoding of the url. It must be "encoded" and the "/" must the code, like so:
https://firebasestorage.googleapis.com/v0/b/*YOURBUCKET*.appspot.com/o/Test**%2F**test.pdf
No more erros.
I got the same problem, and it was actually a security feature.
As the security rules show, I shouldn't have access to the data unless I am authenticated.
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}

How to send Firestore request with request.auth != null with Firebase authentication?

I'm trying to allow users to read and write to my Firestore videoFeedback collection from a web app and getting a "Missing or insufficient permissions" error. How do I make sure that my request to Firestore is sent with the correct user authentication (or any authentication at all)?
This is for an Angular app using Firestore and anonymous Firebase authentication. I have already set up an anonymous user. I would like to add a document to my videoFeedback collection from the web app, not the backend. I've already read the official pages on Firestore docs:
Authenticate Anonymously with Firebase
Get Started with Firebase Authentication on Websites
and many more, plus read all SO questions on this topic.
My Firestore object is already set up correctly (I know because I can read/write to the DB if my security rules don't require a non-null request.auth).
Your help is greatly appreciated.
private db: AngularFirestore;
public initFirebaseApp() {
firebase.initializeApp(this.firebaseConfig);
}
public anonymousAuth() {
firebase.auth().signInAnonymously().catch(function(error) {
console.log("ERROR: " + String(error.errorCode) +
" " + String(error.errorMessage))
});
console.log("User is authorized");
}
this.initFirebaseApp();
this.anonymousAuth();
let date_created = new Date().toLocaleString();
let feedback = {
"feedback": "FAKE_FEEDBACK",
"rating": -1,
'created': date_created,
};
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log(user.uid)
this.db.collection('videoFeedback').add(feedback);
}
}.bind(this));
And my security rules look like this
service cloud.firestore {
match /databases/{database}/documents {
match /videoFeedback/{feedback} {
allow read, write: if request.auth != null;
}
}
}
With this configuration, I get the following output:
User is authorized
JAZe9dsIMtdyNe2dhndleIcn9nd2
ERROR Error: Uncaught (in promise): FirebaseError: [code=permission-denied]: Missing or insufficient permissions.
FirebaseError: Missing or insufficient permissions.
at new FirestoreError (index.cjs.js:352)
at index.cjs.js:7274
at Y.<anonymous> (index.cjs.js:7219)
...
When I replace my security rule with
service cloud.firestore {
match /databases/{database}/documents {
match /videoFeedback/{feedback} {
allow read, write;
}
}
}
I get the same, minus the permissions error. This makes me think that it's an issue with the way my request is being sent, not with the data I'm sending or with the setup of the Firestore database.
User is authorized
JAZe9dsIMtdyNe2dhndleIcn9nd2 (or some random string)
What do I need to do to send my request with a non-null request.auth.uid?

Resources