html - 用户角色的用户身份验证中是否有任何功能?
问题描述
我正在尝试使用 Firebase 为我的网络应用程序创建一个登录界面。我想user role
使用 Firebase 自己的身份验证系统向我的帐户添加一个。(电子邮件)。但它不支持任何添加user role
. 例如“管理员”和“用户”。
这适用于 Firebase(当前为 5.7.2)和 HTML5。
login.js(当前登录认证)
(function(){
var ui = new firebaseui.auth.AuthUI(firebase.auth());
var uiConfig = {
callbacks: {
signInSuccessWithAuthResult: function(authResult, redirectUrl) {
// User successfully signed in.
// Return type determines whether we continue the redirect automatically
// or whether we leave that to developer to handle.
return true;
},
uiShown: function() {
// The widget is rendered.
// Hide the loader.
document.getElementById('loader').style.display = 'none';
}
},
// Will use popup for IDP Providers sign-in flow instead of the default, redirect.
signInFlow: 'popup',
signInSuccessUrl: 'index.html',
signInOptions: [
// Leave the lines as is for the providers you want to offer your users.
firebase.auth.EmailAuthProvider.PROVIDER_ID,
],
};
ui.start('#firebaseui-auth-container', uiConfig);
})()
我希望在 js 中的某处添加一个选项或用户角色的字段作为电子邮件的唯一标识符?(adminabc@xx.com = 管理员,userabc@xx.com = 用户)或 firebase 的附加字段。(在数据库中添加一个专用表,而不是使用实现的用户身份验证。)
解决方案
Firebase Auth 没有“用户角色”API,但您可以通过多种方式在应用程序中实现基于角色的授权。
数据库
正如您所提到的,其中一种方法是将该数据存储在您的数据库中。这样做的好处是它很容易实现。
您可以通过在 Firestore 和实时数据库的数据库规则中进行查找来强制执行这些规则。
实时数据库
{
"rules": {
"adminContent": {
".write": "root.child('users').child(auth.uid).child('admin').val() === true"
}
}
}
火库
service cloud.firestore {
match /databases/{database}/documents {
match /articles/{article} {
allow write: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true
}
}
}
在数据库中维护您的角色和凭据的缺点是您不能跨产品使用该信息。您不能编写访问 RTDB 规则的 Firestore 数据库规则,反之亦然。
自定义声明
如果您希望您的角色跨服务工作(在 RTDB、Firestore 和 Firebase 存储中使用相同的角色数据),那么您应该考虑设置自定义声明,文档中对此进行了很好的解释。
设置完成后,您可以使用自定义声明在不同产品中实现基于角色或组的访问权限。
数据库.rules.json
{
"rules": {
"adminContent": {
".read": "auth.token.admin === true",
".write": "auth.token.admin === true",
}
}
}
firestore.rules / storage.rules
Firestore 和 Storage 规则具有相似的规则语法,您会发现allow
两者的语句相同。
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth.token.admin == true;
}
}
}
推荐阅读
- angularjs - 在 Jasmine 2 中模拟 rxjs 去抖动
- c++ - 添加并设置了滚动区域,但没有出现滚动条
- typescript - Readonly<> 类型的继承
- c# - 试图将图像发送到浏览器但它不工作......:/
- c# - C# bouncycastle AsymmetricCipherKeyPair 到字节数组 ECDSA
- kubernetes - 是否可以在单个 API 调用中应用整个清单
- python - 在字典中创建/附加到列表值的更好方法
- javascript - 防止 jQuery 高级新闻代码中的循环(分叉/修改)
- r - 在插入符号包中使用 LASSO 回归进行归一化会返回奇怪的结果
- apache - 如何在 AEM 中使用具有上下文感知配置的运行模式