1
votes

my app is using this code in flutter to upload images:

final StorageReference imageRef = FirebaseStorage.instance.ref().child('postimages');
    final StorageUploadTask uploadTask = imageRef.child('/' + currentUser.id + '/post_$postid.jpg').putFile(_image);
    var upurl = await (await uploadTask.onComplete).ref.getDownloadURL();
    url = upurl.toString();
    debugPrint('url:$url');

which is working fine if i grant full rewrite access by these unrecommended rules:

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

but if i try to implement any security for example with this rule:

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

    }
  }
}

i end up getting the following exception: [VERBOSE-2:ui_dart_state.cc(177)] Unhandled Exception: PlatformException(Error -13021, FIRStorageErrorDomain, User does not have permission to access gs://picturegramm.appspot.com/postimages/118190432651181005229/post_b050df01-7b58-4016-8d3c-28c7f3ace630.jpg., null)

The app is using firebase authentication with google as sign-in provider. Reading the docs it looks like the auth info is always sent automatically. The signing seems to work perfectly, since i am getting the current user with the userid. So why do the requests fail?

1
Are you sure the user has signed in with google. If the user is signed out this will not work. They must be signed in.Gabe
Any idea how i verify this before uploading? The login seems to be working since i am getting e.g. email, id and profile pic from it.Sebastian
Check if the user exists by final user = FirebaseAuth.instance.currentUser; user will be null if the user isn't logged in.Gabe
ty! it is null. now i have to find out why that is the case after a signing has been completedSebastian
Now at least you have narrowed down the problem. I'm guessing you have some error somewhere in your login logic.Gabe

1 Answers

0
votes

thanks to the comments from Gabe i found out the code is indeed valid, but my authentication was incomplete, since i was not passing the login to firebase. for future reference this the complete login code that is needed to make it work:

  final GoogleSignInAccount googleUser = await GoogleSignIn().signIn();

  // Obtain the auth details from the request
  final GoogleSignInAuthentication googleAuth = await googleUser.authentication;

  // Create a new credential
  final GoogleAuthCredential credential = GoogleAuthProvider.credential(
    accessToken: googleAuth.accessToken,
    idToken: googleAuth.idToken,
  );

  // Once signed in, return the UserCredential
  UserCredential creds = await  FirebaseAuth.instance.signInWithCredential(credential);
  debugPrint('creds:$creds');