提问者:小点点

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;
    }}}

Mycode

    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>

共1个答案

匿名用户

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

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

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

或使用然后使用,例如:

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

或使用回调。

当然,请把它当作伪代码。我不确定你是否可以复制粘贴它,它会工作,无论如何,肯定的功能是异步的,必须以这种方式编码。留档中有很好的例子。