Firebase beforeCreate不添加自定义声明



我正在将Firebase身份验证与Identity Platform一起使用,并试图在创建用户时添加自定义声明。我在谷歌网站上看到了这个例子:设置自定义和会话声明:

exports.beforeCreate = functions.auth.user().beforeCreate((user, context) => {
if (context.credential &&
context.credential.providerId === 'saml.my-provider-id') {
return {
// Employee ID does not change so save in persistent claims (stored in
// Auth DB).
customClaims: {
eid: context.credential.claims.employeeid,
},
// Copy role and groups to token claims. These will not be persisted.
sessionClaims: {
role: context.credential.claims.role,
groups: context.credential.claims.groups,
}
}
}
});

代码是直接的。我正在尝试为所有新用户添加自定义声明,但尚未设置。我不知道该怎么办。这是我的实际代码:

exports.beforeUserCreate = functions.auth.user().beforeCreate((user, context) => {
functions.logger.info('Attempting to set claims for new user', user);
functions.logger.info('Here is the context', context);
return {
customClaims: {
roles: ['user'],
},
sessionClaims: {
roles: ['user'],
},
};
});

我确实在谷歌控制台中看到了日志,所以我知道我的函数正在被调用。我还测试了没有像roles: 'TestRole'这样的数组的声明,但这也不起作用。用户对象只是没有自定义声明。

如果我手动设置索赔,它们确实会按预期显示:

{
"roles": [
"admin",
"subscriber",
"superadmin"
],
"iss": "https://securetoken.google.com/...",
"aud": "xxx",
"auth_time": 1661813313,
"user_id": "xxxx",
"sub": "xxx",
"iat": 1661813313,
"exp": 1661816913,
"email": "xxx",
"email_verified": false,
"firebase": {
"identities": {
"email": [
"xx"
]
},
"sign_in_provider": "password"
}
}

这就是当我尝试自动创建声明时用户对象的样子:

{
"iss": "https://securetoken.google.com/...",
"aud": "xxx",
"auth_time": 1661813351,
"user_id": "xxx",
"sub": "xxx",
"iat": 1661813351,
"exp": 1661816951,
"email": "xxx",
"email_verified": false,
"firebase": {
"identities": {
"email": [
"xxx"
]
},
"sign_in_provider": "password"
}
}

此外,我还尝试独立设置customClaims和sessionClaims。既不会显示在用户对象上,也不会为用户保存自定义声明。

再更新一次。我尝试在beforeCreate中设置显示名称,结果成功了。

return {
customClaims: {
roles: 'pie',
},
displayName: 'pie',
};
// RESULT:
{
"name": "pie",
"iss": "https://securetoken.google.com/...",
"aud": "xxx",
"auth_time": 1661816987,
"user_id": "xxx",
"sub": "xxx",
"iat": 1661816987,
"exp": 1661820587,
"email": "xxx",
"email_verified": false,
"firebase": {
"identities": {
"email": [
"xxx"
]
},
"sign_in_provider": "password"
}
}

来自达尔文的评论:

嗨@Gremash,有一个关于github的公开问题。请参阅sessionClaims内容未添加到解码的令牌中。此外,最近合并了一个关于此问题的修复程序。

相关内容

  • 没有找到相关文章

最新更新