微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Firebase 存储公共 URL 访问被拒绝我需要一个具有公共访问权限的永久 URL makePublic()

如何解决Firebase 存储公共 URL 访问被拒绝我需要一个具有公共访问权限的永久 URL makePublic()

如果访问令牌撤销时处理不当,GetdownloadURL() 将无效。因此我需要一个没有访问令牌的公共访问永久 URL。 如何 makePublic() 某些地方出错了,但我无法得出结论,gcs.bucket("Project-12345.appspot.com").file(fileName).makePublic()

安全规则

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

我的代码

    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    const serviceAccount = require('./ProjectID-12345-firebase-adminsdk-.json');
    admin.initializeApp({
       credential: admin.credential.cert(serviceAccount),databaseURL: "https://ProjectID-12345.firebaseio.com"     
    });
    const {Storage} = require('@google-cloud/storage');
    const gcs = new Storage({
        projectId: "projectId-12345",keyFilename: serviceAccount
    });

    const GetUrl = (productId) => {
        const ImgList = ["ImgA_650x650","ImgB_650x650","ImgC_650x650","ImgD_650x650"] ;
        let url = []
        ImgList.forEach( (element,Index) =>{
             let fileName = "product/"+ productId + "/resize"+ element;
             let storageref = gcs.bucket("Project-12345.appspot.com").file(fileName);
             storageref.makePublic();
             url[Index] = storageref.publicUrl();
        })
        return url;
     }

我得到的 URL 没有访问令牌

[ 'https://storage.googleapis.com/Project-12345.appspot.com/product/1zHTmjNc5CV4WBLDLgdV/resizeImgA_650x650','https://storage.googleapis.com/Project-12345.appspot.com/product/1zHTmjNc5CV4WBLDLgdV/resizeImgB_650x650','https://storage.googleapis.com/Project-12345.appspot.com/product/1zHTmjNc5CV4WBLDLgdV/resizeImgC_650x650','https://storage.googleapis.com/Project-12345.appspot.com/product/1zHTmjNc5CV4WBLDLgdV/resizeImgD_650x650' ]

但问题是 URL 被拒绝访问。将错误显示

此 XML 文件似乎没有任何相关的样式信息。文档树如下所示。

<Error>
<Code>AccessDenied</Code>
<Message>Access denied.</Message>
<Details>Anonymous caller does not have storage.objects.get access to the Google Cloud Storage object.</Details>
</Error>

解决方法

问题可能与 makePublic() 是异步的事实有关,并且在呈现的代码中以同步方式使用它,结果同步的 publicUrl() 在它之前执行。

makePublic() 应该在 await 函数中与 async 一起使用,例如:

const GetUrl = async (productId) => { 
...
   await storageref.makePublic();
...

或使用 then 像:

storageref.makePublic().then(() => url[Index] = storageref.publicUrl());

或回调。

当然请把它当作伪代码。我不确定您是否可以复制粘贴它并且它会起作用,无论如何确保该函数是异步的并且必须以这种方式编码。 documentation 中有很好的例子。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。