具有自定义声明的 Firebase 存储规则

Joh*_*ews 3 python firebase firebase-security firebase-authentication firebase-storage

我无法让 Firebase Storage 使用自定义规则和自定义声明。

在我的 Python 管理面板中,我执行以下操作来创建用户并分配声明 client_id:

# Standard Auth
import firebase_admin
from firebase_admin import db, storage, auth
cred   = firebase_admin.credentials.Certificate('path_to_cert_json')
app    = firebase_admin.initialize_app(cred, 'config')
bucket = storage.bucket(app=app)

# Create User
auth.create_user(email=email) 

# Create custom claims
auth.set_custom_user_claims(uid, {'client_id': client_id})
Run Code Online (Sandbox Code Playgroud)

然后,对于 Firebase 规则,我尝试仅当文件位于具有 client_id 的子文件夹中时才允许用户读取(或下载)文件:

存储上的文件结构:

/{environment}/{client_id}/other_folders_and_files
Run Code Online (Sandbox Code Playgroud)

我设置了以下存储规则:

service firebase.storage {
  match /b/{bucket}/o {
    match /{environment}/{client_id}/{allPaths=**} {
      allow read: if request.auth.token.client_id == client_id
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但这给了我一个错误,即权限被拒绝。

我究竟做错了什么?

笔记:

  • client_id 是正确的,文件夹结构是正确的,已经检查了一百万次。

Esd*_*ier 6

如果我没记错的话,你用错了这个。应该:

service firebase.storage {
  match /b/{bucket}/o {
    match /{environment}/{client_id}/{allPaths=**} {
      allow read: if request.auth.uid == client_id
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

令牌返回其他对象,例如:

  • 电子邮件
  • 电子邮件_已验证
  • 电话号码
  • 姓名

因此,为了能够比较您必须使用的用户 ID request.auth.uid。这种方式将比较客户端的客户端 ID。如果您想查看文档那么一切都是关于request.auth.

编辑

如果您想要自己的自定义令牌,例如:request.auth.token.client_id,您需要在 Python 中使用以下代码来完成此操作:

uid = 'some-uid'
additional_claims = {
    'client_id': your_custom_client_id
}

custom_token = auth.create_custom_token(uid, additional_claims)
Run Code Online (Sandbox Code Playgroud)

然后您可以在存储规则中使用:

service firebase.storage {
  match /b/{bucket}/o {
    match /{environment}/{client_id}/{allPaths=**} {
      allow read: if request.auth.token.client_id == client_id
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

请参阅文档

  • 这些文档很糟糕——它们根本没有解决如何对任何组进行身份验证。仅限个人用户。答案似乎是设置自定义身份验证声明的服务器端函数,但文档从未涉及这一点。 (4认同)