具有自定义声明的Firebase存储规则 [英] Firebase Storage Rules with Custom Claims
问题描述
我无法使Firebase Storage使用自定义规则和自定义声明.
I am unable to get Firebase Storage work with custom rules and using custom claims.
在"Python管理"面板中,我执行以下操作来创建用户并分配声明client_id:
In my Python Admin panel, I do the following to create the user and assign a claim 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})
然后针对Firebase规则,当文件位于具有client_id的子文件夹中时,我尝试允许用户仅读取(或下载)文件:
Then for Firebase rules, I try to allow the user to only read (or download) files when the file is in a subfolder with the client_id:
存储中的文件结构:
/{environment}/{client_id}/other_folders_and_files
我设置了以下存储规则:
I set the following storage rules:
service firebase.storage {
match /b/{bucket}/o {
match /{environment}/{client_id}/{allPaths=**} {
allow read: if request.auth.token.client_id == client_id
}
}
}
但是,这给了我一个错误,即权限被拒绝.
But that gives me an error that Permission is denied.
我在做什么错了?
注意:
- client_id正确且文件夹结构正确,已对此进行了一百万次检查.
推荐答案
如果我没记错,那么您使用的是这个错误.应该是:
If I'm not wrong you are using this wrong. Should be:
service firebase.storage {
match /b/{bucket}/o {
match /{environment}/{client_id}/{allPaths=**} {
allow read: if request.auth.uid == client_id
}
}
}
令牌返回其他对象,例如:
The token returns others objects, like:
- 电子邮件
- 电子邮件已验证
- 电话号码
- 名称
- sub
因此,为了能够比较用户ID,必须使用request.auth.uid
.这种方式将比较cliente客户ID.如果您想看看文档 ,是request.auth
上的所有内容.
So for you be able to compare the user Id you must use request.auth.uid
. This way will compare the cliente client id. If you want to take a look at the docs, is everything abour the request.auth
.
如果您想要自己的自定义令牌,例如:request.auth.token.client_id
,则需要使用Python中的以下代码来完成此操作:
Case you want your own custom token, like: request.auth.token.client_id
, you need do that with this code in Python:
uid = 'some-uid'
additional_claims = {
'client_id': your_custom_client_id
}
custom_token = auth.create_custom_token(uid, additional_claims)
然后您可以在存储规则中使用
Then you can use in your storage rules:
service firebase.storage {
match /b/{bucket}/o {
match /{environment}/{client_id}/{allPaths=**} {
allow read: if request.auth.token.client_id == client_id
}
}
}
请参见文档
这篇关于具有自定义声明的Firebase存储规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!