从另一个Cloud Project调用Firestore数据库显示“权限错误". [英] Calling Firestore Database from another Cloud Project shows "Permission Error"

查看:30
本文介绍了从另一个Cloud Project调用Firestore数据库显示“权限错误".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读完每一个问题之后,可以在线获取文档,我们找不到解决方案,所以在这里发布一个问题.

我们的设置:

  1. 项目FB:仅用于Dev模式下的Firestore.我们希望访问托管在其他云项目中的开发后端服务器中该项目中的数据.

  2. Project GCP:在GAE中部署了应用程序的GCP项目,可以对Project FB的文档进行简单的get()调用.该应用程序是使用Python编写的,并且可以在localhost上完美运行,但在部署后则无法运行.

我们正在测试的示例烧瓶代码:

  route('/test-fb',methods = ['POST','GET'])def test():doc = doc_ref.get()如果doc.exists:打印(u'文档数据:{}'.format(doc.to_dict()))别的:打印(没有此类文件!")返回make_response("Firestore正常工作!") 

注意:

  1. 这不是Firestore规则的问题,因为我们正在使用服务帐户密钥.为了在任何情况下都能100%保证,我们将规则设置为:始终为真

    match/{document = **} {允许读写:如果为真

  2. 我们通过转到设置->服务帐户"来生成服务帐户私钥,并生成新的私钥.然后,在代码上方使用Python中的Admin SDK配置代码段代码.

  3. 意识到所需的服务帐户权限,我们向Project GCP(@appspot)的GAE服务帐户的Project FB IAM帐户添加了许多权限,包括编辑器",存储管理员"和云数据存储所有者".gserviceaccount.com)

  4. 所有Firestore软件包以及任何其他依赖项都更新为最新版本.

  5. 创建了新的密钥以再次测试.对于Project FB,请更新凭据->密钥限制并将其设置为不受限制,以便任何域都可以访问它们.

  6. 删除版本,并在一天中的不同时间再次尝试多次.部署通过Project GCP中触发的云构建进行.云构建成功.另外,除了我们正在阅读Firestore文档(上面的代码)的那条路线之外,所有其他路线均功能正常.

  7. 删除了cookie,并尝试了不同的浏览器.

  8. 也没有尝试使用代码段,而是尝试了google-cloud-firestore软件包:

    解决方案

    我通过一个最小的示例进行了尝试,并且可以正常工作.确保您的GAE应用正在使用应用的默认凭据.

    project-foo 中部署Flask应用,并在 project-bar 中访问Firestore数据库:

    main.py

    从烧瓶导入烧瓶的

     导入firebase_admin从firebase_admin导入凭据从firebase_admin导入firestoreapp = Flask(__ name__)#使用应用程序默认凭据信誉=凭证.ApplicationDefault()firebase_admin.initialize_app(cred,{'projectId':'project-bar',})db = firestore.client()@ app.route('/test-fb',Methods = ['POST','GET'])def test():doc = db.collection('users').document('123').get()如果doc.exists:打印(u'文档数据:{}'.format(doc.to_dict()))别的:打印(没有此类文件!")返回"Firestore有效!"如果__name__ =='__main__': 

    project-foo

    中部署应用

      gcloud set project project-foogcloud应用部署 

    访问 project-foo.uc.r.appspot.com/test-fb .如预期的那样,请参阅日志中的权限被拒绝"错误.

    授予 project-foo 的默认服务帐户访问 project-bar 的Firestore数据库

      gcloud set project项目栏gcloud项目add-iam-policy-binding项目栏\--member serviceAccount:project-foo@appspot.gserviceaccount.com \--role角色/datastore.user 

    等待几分钟以使IAM绑定生效,然后刷新 project-foo.uc.r.appspot.com/test-fb .请参见 Firestore正常工作!.

    After reading every piece of question, documentation available online, we couldn't find a solution, so posting a question here.

    Our Setup :

    1. Project FB: Used only for Firestore in Dev mode. We want to access data from this project in our dev backend server, hosted on a different cloud project.

    2. Project GCP: A GCP Project with app deployed in GAE that makes a simple get() call to Project FB's document. The app is in Python, and it works perfectly in localhost, but not after it's deployed.

    Sample Flask code that we are testing with:

    route('/test-fb', methods=['POST', 'GET'])
    def test():
        doc = doc_ref.get()
        if doc.exists:
            print(u'Document data: {}'.format(doc.to_dict()))
        else:
            print(u'No such document!')
        return make_response("Firestore worked!")
    

    Note:

    1. This is not a question on Firestore Rules, because we are using service account key. To be 100% sure in any case, we have rules set to: true always

      match /{document=**} { allow read, write: if true

    2. We generate the Service Account private key by going to "Settings -> Service Accounts", generate new private key. Then use the Admin SDK config snippet code in Python above our code. This works perfectly in localhost.

    3. Aware of the Service Account permissions needed, we added many permissions including 'Editor', 'Storage Admin' and 'Cloud Datastore Owner' to the Project FB IAM account for GAE service Account of Project GCP (@appspot.gserviceaccount.com)

    4. All the Firestore packages, any other dependency are updated to the latest version.

    5. Created new keys to test again. For Project FB, updated Credentials -> Key restrictions and set them to unrestricted so any domains can access them.

    6. Deleted the versions, and tried again many times at different times of the day as well. The deployments happen through triggered cloud builds in Project GCP. The cloud builds are successful. Also, all routes function perfectly except the one in which we are reading the Firestore document (code above).

    7. Deleted cookies, and tried different browsers.

    8. Instead of using the snippet code, also tried the google-cloud-firestore package: https://pypi.org/project/google-cloud-firestore/

    9. Both the projects are in the same location (US multilocation)

    Please advise on what we could be doing wrong, and what else we can try? We are lost at this point, and this simple task has taken us several days, and we've tried all permutations of above steps multiple times to double check.

    GAE Response on a request to the server:

    解决方案

    I tried this with a minimal example and it worked. Make sure your GAE app is using the application default credentials.

    Deploying a Flask app in project-foo with access to a Firestore DB in project-bar:

    main.py

    from flask import Flask
    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore
    
    app = Flask(__name__)
    
    # Use the application default credentials
    cred = credentials.ApplicationDefault()
    firebase_admin.initialize_app(cred, {
      'projectId': 'project-bar',
    })
    
    db = firestore.client()
    
    @app.route('/test-fb', methods=['POST', 'GET'])
    def test():
        doc = db.collection('users').document('123').get()
        if doc.exists:
            print(u'Document data: {}'.format(doc.to_dict()))
        else:
            print(u'No such document!')
        return 'Firestore worked!'
    
    if __name__ == '__main__':
    

    Deploy app in project-foo

    gcloud set project project-foo
    gcloud app deploy
    

    Visit project-foo.uc.r.appspot.com/test-fb. As expected, see permission denied error in logs.

    Give project-foo's default service account access to project-bar's Firestore DB

    gcloud set project project-bar
    gcloud projects add-iam-policy-binding project-bar \
      --member serviceAccount:project-foo@appspot.gserviceaccount.com \
      --role roles/datastore.user
    

    Wait a few minutes for IAM binding to take hold, refresh project-foo.uc.r.appspot.com/test-fb. See Firestore worked!.

    这篇关于从另一个Cloud Project调用Firestore数据库显示“权限错误".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆