[英]Firebase Admin SDK: Set / Merge Custom User Claims
Does Firebase have any trick like { merge: true }
to set extra/more custom claims without delete/override the old variables? Firebase 是否有任何技巧,例如
{ merge: true }
来设置额外/更多自定义声明而不删除/覆盖旧变量?
Step to reproduce:重现步骤:
admin.auth().setCustomUserClaims(uid, { a: 'value' }) // Run this first
admin.auth().setCustomUserClaims(uid, { b: 'value' }) // Then run this after
Result:结果:
{ b: 'value'}
Expected result :预期结果:
{ a: 'value', b: 'value' }
Or I did something wrong?还是我做错了什么?
The Firebase documentation for setCustomUserClaims
states: setCustomUserClaims
的 Firebase 文档指出:
- customUserClaims : Object
customUserClaims :对象
The developer claims to set.开发商声称设置。 If null is passed, existing custom claims are deleted.
如果传递 null,则删除现有的自定义声明。 Passing a custom claims payload larger than 1000 bytes will throw an error.
传递大于 1000 字节的自定义声明负载将引发错误。 Custom claims are added to the user's ID token which is transmitted on every authenticated request.
自定义声明被添加到用户的 ID 令牌中,该令牌在每个经过身份验证的请求上传输。 For profile non-access related user attributes, use database or other separate storage systems.
对于配置文件非访问相关的用户属性,使用数据库或其他单独的存储系统。
It isn't entirely clear from this description, but the statement, "If null is passed, existing custom claims are deleted," provides a hint that the custom claims are completely overwritten with each call to setCustomUserClaims
.从这个描述中并不完全清楚,但声明“如果传递 null,现有的自定义声明将被删除”提供了一个提示,即每次调用
setCustomUserClaims
完全覆盖自定义声明。
Therefore, custom claims need to be set as follows:因此,自定义声明需要设置如下:
claims = {
a: 'value',
b: 'value'
}
admin.auth().setCustomUserClaims(uid, claims)
addCustomUserClaims
addCustomUserClaims
A helper function could be created to merge in new claims.可以创建一个辅助函数来合并新的声明。
async function addCustomUserClaims(uid, claims) {
const user = await admin.auth().getUser(uid)
let updated_claims = user.customClaims || {}
for (let property in claims) {
if (Object.prototype.hasOwnProperty.call(claims, property)) {
updated_claims[property] = claims[property]
}
}
await admin.auth().setCustomUserClaims(uid, updated_claims)
}
Christopher Peisert's answer is correct, but it can be done much more cleanly as Christopher Peisert 的回答是正确的,但它可以做得更干净,因为
admin.auth().getUser(uid).then(({customClaims: oldClaims}) =>
admin.auth().setCustomUserClaims(uid, { ...oldClaims, b: 'value' }))
If you want to abstract this logic into a function, it can be done as如果你想把这个逻辑抽象成一个函数,可以这样做
function addCustomUserClaims(uid, claims) {
return admin.auth().getUser(uid).then(({customClaims}) =>
admin.auth().setCustomUserClaims(uid, { ...customClaims, ...claims }))
}
or equivalently* as或等效地*为
const addCustomUserClaims = (uid, claims) =>
admin.auth().getUser(uid).then(({customClaims}) =>
admin.auth().setCustomUserClaims(uid, { ...customClaims, ...claims }))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.