【问题标题】:Flutter: implement any authentication in Firebase storage with google authentication failsFlutter:使用谷歌身份验证在 Firebase 存储中实施任何身份验证失败
【发布时间】:2023-03-10 16:40:01
【问题描述】:

我的应用在 Flutter 中使用此代码上传图片:

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');

如果我通过这些不推荐的规则授予完全重写访问权限,那么它工作正常:

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

但如果我尝试使用此规则实施任何安全性:

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

    }
  }
}

我最终得到以下异常: [VERBOSE-2:ui_dart_state.cc(177)] 未处理的异常:PlatformException(错误 -13021,FIRStorageErrorDomain,用户无权访问 gs://picturegramm.appspot.com/postimages/118190432651181005229/post_b050df01-7b58-4016- 8d3c-28c7f3ace630.jpg., null)

该应用使用 Google 作为登录提供商的 Firebase 身份验证。 阅读文档,似乎 auth 信息总是自动发送。 签名似乎工作得很好,因为我正在使用用户 ID 获取当前用户。 那么为什么请求会失败?

【问题讨论】:

  • 您确定用户已使用谷歌登录。如果用户退出,这将不起作用。他们必须登录。
  • 知道我在上传之前如何验证这一点吗?登录似乎正在工作,因为我得到例如电子邮件、身份证和个人资料图片。
  • 通过final user = FirebaseAuth.instance.currentUser;检查用户是否存在,如果用户没有登录,user将为空。
  • 泰!它是空的。现在我必须在签名完成后找出为什么会这样
  • 现在至少你已经缩小了问题的范围。我猜你在登录逻辑的某个地方有错误。

标签: firebase flutter firebase-authentication firebase-storage


【解决方案1】:

感谢 Gabe 的 cmets,我发现代码确实有效,但我的身份验证不完整,因为我没有将登录信息传递给 firebase。 以供将来参考,这是使其工作所需的完整登录代码:

  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');

【讨论】:

    猜你喜欢
    • 2019-06-16
    • 2018-01-01
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    相关资源
    最近更新 更多