【问题标题】:Is there any function in User Authentication for User Roles?用户角色的用户身份验证中是否有任何功能?
【发布时间】:2019-01-03 10:46:20
【问题描述】:

我正在尝试使用 Firebase 为我的网络应用创建登录界面。我想使用 Firebase 自己的身份验证系统将 user role 添加到我的帐户中。 (电子邮件)。但它不支持添加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 = admin, userabc@xx.com = user) 或 firebase 的附加字段。 (在数据库中添加一个专用表,而不是使用实现的用户身份验证。)

【问题讨论】:

    标签: html firebase firebase-authentication


    【解决方案1】:

    Firebase 身份验证没有“用户角色”API,但您可以通过多种方式在应用中实现基于角色的授权。

    数据库

    正如您所提到的,其中一种方法是将该数据存储在您的数据库中。这样做的好处是易于实施。

    您可以通过在您的数据库规则中查找 Firestore 和实时数据库来强制执行这些规则。

    Realtime database

    {
      "rules": {
        "adminContent": {
          ".write": "root.child('users').child(auth.uid).child('admin').val() === true"
        }
      }
    }
    

    Firestore

    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 存储中使用相同的角色数据),那么您应该考虑设置自定义声明,这在 in the documentation 中有很好的解释。

    设置完成后,您可以使用自定义声明在不同的产品中实施基于角色的声明或group access rights

    database.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;
        }
      }
    }
    

    【讨论】:

    猜你喜欢
    • 2016-11-03
    • 2020-10-17
    • 1970-01-01
    • 2018-05-25
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-30
    相关资源
    最近更新 更多