【问题标题】:Authentication error using Firebase Admin SDK with Python使用带有 Python 的 Firebase Admin SDK 的身份验证错误
【发布时间】:2023-03-14 11:15:01
【问题描述】:

我正在尝试将 Firebase 与 Python 的官方 Admin SDK (https://firebase.google.com/docs/database/admin/start) 连接。

但是,我做错了,因为我没有获得授权

这是我的代码:

import firebase_admin
from firebase_admin import credentials
from firebase_admin import db

# Fetch the service account key JSON file contents
cred = credentials.Certificate('./ServiceAccountKey.json')

# Initialize the app with a None auth variable, limiting the server's access
firebase_admin.initialize_app(cred, {
    'databaseURL': 'https://*[database name]*.firebaseio.com',
    'databaseAuthVariableOverride': None
})

# The app only has access to public data as defined in the Security Rules
ref = db.reference('/public_resource')
print(ref.get())

这是我得到的错误:

python3 firebase_test.py 
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/firebase_admin/db.py", line 943, in request
    return super(_Client, self).request(method, url, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/firebase_admin/_http_client.py", line 117, in request
    resp.raise_for_status()
  File "/usr/local/lib/python3.6/site-packages/requests/models.py", line 941, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://*[database name]*.firebaseio.com/public_resource.json?auth_variable_override=null

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "firebase_test.py", line 16, in <module>
    print(ref.get())
  File "/usr/local/lib/python3.6/site-packages/firebase_admin/db.py", line 222, in get
    return self._client.body('get', self._add_suffix(), params=params)
  File "/usr/local/lib/python3.6/site-packages/firebase_admin/_http_client.py", line 129, in body
    resp = self.request(method, url, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/firebase_admin/db.py", line 945, in request
    raise _Client.handle_rtdb_error(error)
firebase_admin.exceptions.UnauthenticatedError: Unauthorized request.

我使用的是安装了 Python 3.6 的 Raspberry Pi 4 B。

有人能给我指出为什么会发生这种情况以及如何解决它的正确方向吗?

【问题讨论】:

    标签: python firebase sdk admin


    【解决方案1】:

    发现了!

    在数据库下,转到规则并将其更改为:

    {
      /* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
      "rules": {
        ".read": true,
        ".write": true
      }
    }
    

    自从我上次访问以来等待了太长时间后,它被自动设置为 false。

    【讨论】:

      猜你喜欢
      • 2019-07-09
      • 2019-09-01
      • 1970-01-01
      • 2020-07-25
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 2017-08-13
      • 2018-04-13
      相关资源
      最近更新 更多