Flutter & Firebase - using firebase_storage along with firebase_auth

安稳与你 提交于 2020-02-06 16:55:03

问题


Working with the firebase packages: https://pub.dartlang.org/packages/firebase_auth https://pub.dartlang.org/packages/firebase_storage

I can sign into firebase using firebase_auth, and everything works great there, but when I use the firebase_storage package to upload a file I get access denied and I have to go into firebase and set the permissions to:

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

This is not ideal for an application that uses authentication, how do I tell the firebase_storage package that I am authenticated via the firebase_auth package?


回答1:


You should not have that problem, I share a code that works for me.

Future<Null> ensureLoggedIn() async {
  FirebaseUser firebaseUser = await auth.currentUser();
  assert(firebaseUser != null);
  assert(!firebaseUser.isAnonymous);
}

Future<String> uploadFile(File file) async {
    assert(file != null);
    await ensureLoggedIn();
    int random = new Random().nextInt(100000);
    String _instance = '/files/image_$random.jpg';

    StorageReference ref = FirebaseStorage.instance.ref().child(_instance);
    StorageUploadTask uploadTask = ref.putFile(file);

    final Uri downloadUrl = (await uploadTask.future).downloadUrl;

    return downloadUrl.toString();
  }


来源:https://stackoverflow.com/questions/50995023/flutter-firebase-using-firebase-storage-along-with-firebase-auth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!