【问题标题】:How to upload files to Firebase Storage using a userId and token obtained through using the REST API如何使用通过使用 REST API 获得的 userId 和令牌将文件上传到 Firebase 存储
【发布时间】:2020-02-28 10:16:38
【问题描述】:

我正在尝试上传文件以将图像上传到 Firebase 存储,其规则是用户只能写入自己的用户配置文件。以下是我的存储规则

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

但是,当我上传图片时,我收到拒绝访问错误。我确信我已经涵盖了所有其他角度来解释为什么它出错了。我能想到的唯一一件事是我的用户 ID 没有正确发送到 Firebase 存储。我通过发送 POST 请求获得了我的令牌和 UserId。这是我的注册功能

return async dispatch => {
        const response = await fetch(
            'https://identitytoolkit.googleapis.com/v1/accounts:signUp?key={MYKEY}',
            {
                method: 'POST',
                headers: {
                    'Content-Type' : 'application/json'
                },
                body: JSON.stringify({
                    email: email,
                    password: password,
                    returnSecureToken: true
                })
            }
        );
        if (!response.ok) {
            const errorData = await response.json()
            const errorId = errorData.error.message;
            let message = 'Something went wrong!'
            if (errorId === 'EMAIL_EXISTS') {
                message = 'The email entered already exists';
            }
            throw new Error(message);
        }
        const resData = await response.json()
      dispatch(authenticate(resData.localId,resData.idToken,parseInt(resData.expiresIn) * 1000, resData.refreshToken))

您从 REST API 和 firebase 存储中获得的令牌和用户 ID 是否存在兼容性问题。如果有,将图像上传到 Firebase 存储的解决方案是什么。

这也是我的uploadImage函数。

const uploadImage = async (uri, name) => {
        const response = await fetch(uri);
        const blob = await response.blob();
        console.log(response)
        console.log(blob)
        var storageRef = firebase.storage().ref();
        var profilePhotoRef = storageRef.child(`users/${uid}/${name}`);
        return profilePhotoRef.put(blob);
    };

谢谢。

【问题讨论】:

  • 所以您根本没有使用 Firebase 身份验证 SDK?
  • 嗨。我使用这里的东西。 firebase.google.com/docs/reference/rest/auth。不完全确定它的 Firebase 身份验证 SDK 是否,因为我对原生和应用程序开发反应仍然很陌生。

标签: firebase rest react-native google-cloud-storage firebase-storage


【解决方案1】:

只有当您使用 Firebase Authentication SDK 登录用户时,用户 ID 才会与文件上传和下载一起发送,以用于安全规则。使用 REST API 进行手动身份验证将不起作用。

【讨论】:

    猜你喜欢
    • 2016-10-04
    • 2022-08-18
    • 2020-11-26
    • 1970-01-01
    • 2018-01-19
    • 2022-08-18
    • 2017-07-03
    • 2021-08-16
    • 1970-01-01
    相关资源
    最近更新 更多