how do I implement role based access control in firebase

后端 未结 3 1315
死守一世寂寞
死守一世寂寞 2020-11-28 05:45

This is my first foray into Firebase & nosql, I come from a SQL background.

Using Simple Login Security Email/Password, how do I limit access to data in Firebase

相关标签:
3条回答
  • 2020-11-28 05:58

    Looking at this again a year later "Custom Tokens" may be a better option.

    https://www.firebase.com/docs/security/guide/user-security.html#section-custom

    0 讨论(0)
  • 2020-11-28 06:13

    There isn't a way to attach permissions directly to the auth variable (or at least that doesn't seem to be an intended strategy). I'd recommend creating a collection of users organized by auth.uid and you can keep whatever kind of permission attributes you want in there, such that your security rules might something look like this (untested):

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

    Where role is an attribute belonging to all objects in your users collection.

    UPDATE

    See comment below:

    "There isn't a way to attach permissions directly to the auth variable" This changed in 2017. You can now attach custom claims to an auth profile, which are available in security rules. See bojeil's answer and the Firebase documentation for custom claims. – Frank van Puffelen

    0 讨论(0)
  • 2020-11-28 06:17

    Firebase launched support for role based access on any user via custom user claims on the ID token: https://firebase.google.com/docs/auth/admin/custom-claims

    You would define the admin access rule:

    {
      "rules": {
        "adminContent": {
          ".read": "auth.token.admin === true",
          ".write": "auth.token.admin === true",
        }
      }
    }
    

    Set the user role with the Firebase Admin SDK:

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

    This will propagate to the corresponding user's ID token claims. You can force token refresh immediately after: user.getIdToken(true)

    To parse it from the token on the client, you need to base64 decode the ID token's payload: https://firebase.google.com/docs/auth/admin/custom-claims#access_custom_claims_on_the_client

    You can upgrade/downgrade users as needed. They also provided a programmatic way to list all users if you have recurring scripts to change a users' access levels: https://firebase.google.com/docs/auth/admin/manage-users#list_all_users

    0 讨论(0)
提交回复
热议问题