【问题标题】:Authenticate Google Firestore in Cloud Functions (Python)在 Cloud Functions (Python) 中对 Google Firestore 进行身份验证
【发布时间】:2020-03-20 07:48:51
【问题描述】:

我正在使用 Google Cloud Function 使用 Cloud Scheduler 以设定的时间间隔对我的 Firestore 集合执行一些操作(都在同一个项目中)。

它的功能本身可以正常工作并进行身份验证。但是,我在我的 python 代码中使用服务帐户 JSON 进行身份验证,如下所示:

cred = credentials.Certificate({
  "type": "service_account",
  "project_id": "...",
  "private_key_id": "...",
  "private_key": "...",
  "client_email": "...",
  "client_id": "...",
  "auth_uri": "...",
  "token_uri": "...,
  "auth_provider_x509_cert_url": "...",
  "client_x509_cert_url": "..."
})
firebase_admin.initialize_app(cred)
db = firestore.client()

我知道有更好的身份验证方法,因为数据库和函数位于同一个 Google Cloud 项目中。但是,我找不到任何有关如何通过内联编辑器执行此操作的文档。

如何在不使用服务帐户的情况下验证并引用我的 Firestore 数据库?

【问题讨论】:

  • 您是否检查过来自 Google 的 Python 示例以获得 GCP? link 您可以在此处找到 Cloud Functions 和 Firestore 的代码 sn-ps。

标签: python-3.x firebase google-cloud-platform google-cloud-firestore google-cloud-functions


【解决方案1】:

每个云功能都有一个身份,由分配给它的服务帐户定义。默认情况下,云功能将分配给 AppEngine 默认服务帐户。您需要创建一个具有与Firestore 交互所需角色的服务帐户,并使用 CLI 或控制台将其分配给云功能。

有关 Firestore 所需的权限,请参阅以下内容-

https://cloud.google.com/firestore/docs/security/iam

如果您不知道如何创建服务帐户-

https://cloud.google.com/iam/docs/creating-managing-service-accounts

最后,将自定义身份分配给云功能-

https://cloud.google.com/functions/docs/securing/function-identity#per-function_identity

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    您的 Cloud Function 必须使用服务帐号才能连接到 Firestore。通常这是 ID 为 PROJECT_ID@appspot.gserviceaccount.com 的 App Engine 默认服务帐户。如果您想使用其他服务帐户,则可以分配一个per-function identity

    因此,您的代码实际上不需要创建凭证或类似的东西。看看这个(非官方)community tutorial 的工作示例。您可以将 Javascript 替换为下面提供的 Python 代码示例或查看GitHub examples repo 中的 sn-ps:

    from google.cloud import firestore
    
    # Add a new document
    db = firestore.Client()
    doc_ref = db.collection(u'users').document(u'alovelace')
    doc_ref.set({
        u'first': u'Ada',
        u'last': u'Lovelace',
        u'born': 1815
    })
    
    # Then query for documents
    users_ref = db.collection(u'users')
    
    for doc in users_ref.stream():
        print(u'{} => {}'.format(doc.id, doc.to_dict()))
    

    【讨论】:

    • Github 示例仓库,链接已损坏。可以更新一下吗?
    • @jkr 我用新链接更新了我的答案
    【解决方案3】:

    Python 示例如下所示,如何从谷歌云函数将文档添加到 Firestore。在云函数中,内联编辑器,在 ma​​in.py

    中添加以下函数
    def add_document_to_firestore():
        from google.cloud import firestore
        db = firestore.Client()
        doc_ref = db.collection(u'collectionName').document(u'documentID')
        doc_ref.set({
            u'column1': u'value1',
            u'first': u'Mathison',
            u'last': u'Turing',
            u'born': 1912
        })
    

    requirements.txt文件中,添加

    google-cloud-firestore==2.0.2
    

    您现在可以将参数添加到上述函数并从应用程序调用此云函数 URL。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-09
      • 2018-07-23
      • 1970-01-01
      • 1970-01-01
      • 2020-10-25
      • 1970-01-01
      • 2019-10-27
      • 2022-01-28
      相关资源
      最近更新 更多