You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pyrebase下载Firebase Storage文件遇权限认证问题求助

问题:Pyrebase下载Firebase Storage文件在认证规则下失败

问题背景

使用Pyrebase从Firebase Storage下载文件时,当Storage规则设为公开读写时代码能正常运行;但切换到需要用户认证的规则(无论是仅允许已认证用户,还是匹配用户UID的规则),下载操作直接失败。

原代码示例

firebaseConfig={'apiKey': "example",
                'authDomain': "example",
                'databaseURL': "example",
                'projectId': "example",
                'storageBucket': "example",
                'messagingSenderId': "example",
                'appId': "example",
                'measurementId': "example"}
firebase=pyrebase.initialize_app(firebaseConfig)
db = firebase.database()
auth=firebase.auth()
email = 'example@gmail.com'
password = 'password123'
login = auth.sign_in_with_email_and_password(email, password)
storage = firebase.storage()        
storage.child('customers/DNOgkWW8yRUaEZXko2S2EPEIiBR2/k.txt').download(path="C:\Users\username\Desktop\test", filename='k.txt')

测试过的Storage规则

  1. 匹配用户UID的规则(失败):
rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /customers/{userId}/{allPaths=**} {
      allow read: if request.auth.uid == userId;
   }
  }
 }
  1. 允许所有已认证用户的规则(失败):
rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /customers/{userId}/{allPaths=**} {
      allow read, write: if request.auth != null
   }
  }
 }

问题原因

Pyrebase的Storage模块不会自动把用户登录后的认证令牌附加到存储操作请求里,导致Firebase Storage的安全规则无法识别用户的认证状态,request.auth返回null,触发权限拒绝。

解决方案

调用download方法时,显式传入用户登录后获取的idToken参数,让Firebase验证用户的认证状态。同时建议动态拼接文件路径,避免硬编码UID带来的错误。

修改后的代码示例

firebaseConfig={'apiKey': "example",
                'authDomain': "example",
                'databaseURL': "example",
                'projectId': "example",
                'storageBucket': "example",
                'messagingSenderId': "example",
                'appId': "example",
                'measurementId': "example"}
firebase=pyrebase.initialize_app(firebaseConfig)
auth=firebase.auth()
email = 'example@gmail.com'
password = 'password123'

# 用户登录并获取认证信息
login = auth.sign_in_with_email_and_password(email, password)
# 获取当前用户的UID,用于动态拼接文件路径
user_uid = login['localId']

storage = firebase.storage()        
# 调用download时传入idToken,附带认证信息
storage.child(f'customers/{user_uid}/k.txt').download(
    path="C:\\Users\\username\\Desktop\\test", 
    filename='k.txt',
    token=login['idToken']
)

注意事项

  1. 若使用匹配UID的规则,必须确保文件路径中的userId与登录用户的localId完全一致,动态拼接路径能有效避免手动输入错误。
  2. 测试时可先使用allow read, write: if request.auth != null规则验证认证是否生效,确认没问题后再细化到UID匹配的规则。

内容的提问来源于stack exchange,提问作者Tristan Fogle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 17:57:50