gpt4 book ai didi

javascript - Firebase - 防止基于 Angular 色的身份验证

转载 作者:行者123 更新时间:2023-12-01 02:28:01 24 4
gpt4 key购买 nike

我正在开发一个适用于 Android 和 Web 的应用程序。在 Web 上,只有管理员用户才能登录。我想阻止非管理员用户登录网络应用程序。

我发现让它“起作用”的唯一方法是当我获得有关用户 Angular 色的信息时注销该用户。问题是这会使页面闪烁,因为在几秒钟内用户已通过身份验证。我想阻止登录,但只有登录后我才能访问 User 对象。这是我当前的代码:

export function login (email, pw) {
return firebaseAuth.signInWithEmailAndPassword(email, pw).then(checkRole)
}

function checkRole (user) {
return ref.child(`UserRoles/${user.uid}`).once('value').then(snapshot => {
let isAdmin = (snapshot.val() && snapshot.val().admin)
if (!isAdmin) throw new Error('User is not admin')
}).then(() => user)
}

尽管这会触发 Promise 的 catch block ,但身份验证仍然完成。有什么办法可以预防吗?

最佳答案

您最好使用 custom user claims您对用户进行设置以定义用户 Angular 色。

您可以通过 Admin SDK 设置自定义声明:

admin.auth().setCustomUserClaims(uid, {role: 'admin'}).then(() => {
// The new custom claims will propagate to the user's ID token the
// next time a new one is issued.
});

然后,您可以通过安全规则强制访问,而无需进行任何查找:

{
"rules": {
"data": {
"$user_id": {
".read": "$user_id === auth.uid && auth.token.role === 'admin'",
".write": "$user_id === auth.uid && auth.token.role === 'admin'"
}
}
}
}

这是这里的关键, Angular 色访问必须在服务器端强制执行。

在客户端,您可以获取 ID token currentUser.getIdToken() 并对有效负载进行 Base64 解码,以检查声明中的 Angular 色,从而相应地更新 UI,但这只是美观和客户端无法信任,应在服务器端强制执行访问。

关于javascript - Firebase - 防止基于 Angular 色的身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48572474/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com