Photo: www.softwaresuggest.com/blog/altern…

Author: Meng Jin

preface

When it comes to background system, authority management system is an indispensable part. There is a lot of data in the background (including a lot of private data), and this data is usually managed separately by people with different responsibilities. A good permission design can ensure the smooth processing of business data, reduce operational risks, and ensure data security.

In the background application I was responsible for recently, there happened to be the part of permission design. The author took this opportunity to sort out a brief outline of the permission system. Today, I will make an introduction to the permission system and practice in the project around the outline.

Introduction to permission System

1. What are permissions

I understand that permission is essentially access control. A sentence is used to describe whether a subject can perform certain operations on certain resources according to certain rules. From this sentence, it can be clearly seen that there are three elements that constitute permission: subject, resource and operation.

2. Permission division

Permissions can be roughly divided into: page permissions, function permissions and data permissions

  • Page permissions: the user’s access to pages, modules, menus, and so on
  • Function permissions: related to page permissions. Only page permissions have corresponding function permissions. Any interaction, such as adding, deleting, modifying, and searching, can of course be more fine-grained to the interface level permissions
  • Data permissions: Controls the permissions of different subjects to view different data information. Compared with the above two permissions, data permissions are closely related to service logic. Different system data permissions are different, which is the most complicated part. Data permissions can be broadly branch and column permissions, that is, different subjects can see different rows and fields in the data table based on different conditional rules.

3. Permission model

Four classic permission models: Autonomous access control (DAC), mandatory access control (MAC), role-based access control (RBAC) and attribute based access control (ABAC) are the most widely used RBAC models at present. This paper also mainly introduces this model, but based on the integrity of the article, it will make a simple summary of the other types.

  • DAC: Determine what operations users can perform on resources according to the permission control list or permission control matrix. Users are directly associated with permissions. Users with permissions also have the right to allocate permissions
  • MAC: To compensate for the defect of DAC, each object and user will have a permission level identification, suitable for confidential or hierarchical organizations
  • ABAC: a complex model that dynamically calculates one or a group of attributes to determine whether certain conditions are met for authorization

4. Introduction to RBAC model

Traditional mode and resource permissions directly related permissions change will lead to redistribution of each subject, and RBAC model in the user introduced the concept of role between subject and authority, through the way of users association roles, roles, permissions associated indirectly gives permission, thus achieve the goal of users and permissions decoupling. (See below)

  • RBAC0: The core basic idea that users are associated by roles and permissions. It’s a many-to-many relationship
  • RBAC1: introduces the concept of role inheritance on the basis of 0. A high-level role can inherit the rights of a low-level role
  • RBAC2: added permission constraint on the basis of 1, divided into static responsibility separation and dynamic responsibility separation
    1. Static separation of responsibilities: Users cannot simultaneously be assigned conflicting roles
    2. Dynamic separation of responsibilities: Conflicting roles cannot be activated simultaneously in a session
  • RBAC3: is the combination of 1 and 2

The project practice

1. The background

In do internal back-end systems, you need to implement a system of rights to manage, at the beginning of the project because of its simple function of a single, interactive, using a number of reasons, such as less permissions are directly on the user model (DAC), but with functional iteration, interactive complicated, more and more high to the requirement of access control, the original plan has can’t meet, Therefore, the entire permissions need to be redesigned based on the RBAC model.

2. (

In the actual development, it was found that implementing a set of permissions scheme in business code would encounter the following problems:

  • You need to initialize some roles and permission tables yourself when the project is initially launched
  • To add or delete assigned roles or permissions, you need to maintain the association between tables
  • For URL-level interception, you need to do some role permissions at the Controller layer (or middleware) yourself
  • The relationship between role resource permissions cannot be directly seen in the project
  • In addition to cloud music, there are other apps, such as live broadcast and Karaoke, etc. Even if the same resource can be seen by different apps, different fields or data lines need to be returned according to roles in the code
  • The permission judgment code and the business logic code are heavily coupled, which is not conducive to maintenance

Practice 3.

3.1 Generating an ACCESS control Table

How to describe the relationship between resource role permissions through an access control table is a core idea of the later plug-in implementation

  1. Think about what initial roles exist in the project

    ['admin'.'music_bridge_ios_developer'.'music_bridge_admin'.'music_link_developer']
    Copy the code
  2. Which resources can be operated by these roles

    [{
      roles: ['admin'].allow: The '*'
    }, {
      roles: ['music_bridge_ios_developer'].allow: {
        resources: ['bridge']}}, {roles: ['music_bridge_admin'].allow: {
        resources: ['bridge']}}, {roles: ['music_link_developer'].allow: {
        resources: ['link']}}]Copy the code
  3. What operations can be performed on these resources

    [{
      roles: ['music_bridge_ios_developer'].allows: [{
        resources: ['bridge'],
    +   actions: ['get'.'post'.'update'.'delete']]}}, {roles: ['music_bridge_admin'].allows: [{
        resources: ['bridge'],
    +   actions: The '*'}}]]Copy the code
  4. Whether these resources are restricted by conditional rules, such as only certain lines or certain fields

    [{
      roles: ['music_bridge_ios_developer'].allow: {
        resources: ['bridge'].actions: ['get'.'post'.'update'.'delete'],
    +   attributes: ['id'.'name'],
    +   where: [{
          platform: 'ios'.app: 'music'}}}]]Copy the code
  5. Whether permission control is required for URL routes

    apis: [{
        url: '/api/bridge'.roles: ['music_bridge_ios_developer'.'music_bridge_admin']}]Copy the code

Above we have generated a simple access control table, in which the relationship between the resource role permissions is clear at a glance.

3.2 an Egg plug-in

Combined with the ABOVE RBAC model and access control tables, an Egg plug-in is packaged based on Egg and MySQL to centrally manage permission issues encountered in a project.

The plug-in solves the following problems:

  • Database configuration, Scheme model definition
  • You can use a configuration table to maintain the relationship between role resource permissions
  • Initializes the role table, permission table, and role permission association table at startup based on the configuration table
  • Super administrator with the highest rights
  • Support for URL – and API-level intercept permission control
  • You can configure data permissions for roles and customize filtering rules
  • User roles and permissions are managed through apis
  • You can configure the parent role. The parent role has the rights of the child role
  • Error message when customizing unauthorized limit
  • Check whether there are users under the role when deleting the role
Complete code:
  1. // config.default.js
    // The role permission can be initialized according to the configuration or dynamically changed
    // Automatically generate table relationships based on the configuration
    // The data permissions are directly linked to the role, and the functional permissions are separate tables
    
    config.acl = {
      // Database configuration
      db: {
            database: 'test'.host: '127.0.0.1'.port: '3331'.username: 'root'.password: 'root',},apis: [{
        url: '/api/bridge'.// Intercept the request
        roles: ['music_bridge_ios_developer'.'music_bridge_admin'].// Configure the role required to access the URL
        validator: () = > {} // Custom validation functions can be supported later}].// Permission configuration
      permissions: [{
        roles: ['admin'].allows: The '*' // * Indicates that you have all permissions
      }, {
        // Cloud Music Bridge ios developer
        roles: ['music_bridge_ios_developer'].allows: [{
          resources: ['bridge'].// The resource is bridge
          actions: ['get'.'post'.'update'.'delete'].// Operations allowed by this role on this resource
          attributes: ['id'.'name'].// Control the column permissions of data permissions, return only id and name fields
          where: [{
            platform: 'ios'.app: 'music'}].// Supports simple row permission control. This role only returns bridge resources where app is Music and platform is ios}].parents: ['music_developer'] // If yes, configure the parent role
      }, {
        roles: ['music_bridge_admin'].// Bridge administrator
        allows: [{
          resources: ['bridge'].actions: The '*' // This role has all operation rights for the resource}}]].errorhandler: ' ' || () = > {} // Customize error messages
    }
    Copy the code
  2. The following data tables are automatically generated based on the configuration

    Character sheet

    Permissions on the table

    Role permission association table

    Url role association table

  3. You can manage users, roles, and permissions through apis in your code

    // Add a user to the role
    await this.app.acl.addUserToRoles(userId, ['music_bridge_admin'])
    
    // Add a new role
    await this.app.acl.addRoles(['look_bridge_developer'] and {allows: [{
        resources: 'bridge'.actions: ['get'.'post'.'update']
        where: [{
          platform: 'look'}}}]]);// Add xx permission for a resource to a role
    await this.app.acl.addPermsToRole('look_bridge_developer'.'bridge'['delete']);
    
    // Get all roles of the user
    await this.app.acl.getUserRoles(userId);
    
    // Obtain all permissions of a user on a resource
    await this.app.acl.getUserResourcePermissions(userId, 'bridge');
    
    // Check whether the user has the permission to delete a resource
    await this.app.acl.hasPermissions(userId, 'bridge'.'delete')... There are other waysCopy the code

The design idea of the plug-in is to maintain the relationship between the resource permissions of roles in a configuration way, bind the access rules of data permissions to roles, and create table associations according to the configuration information when the plug-in is initialized. The exposed API allows users to manage permissions without worrying about how to update the relationship, decoupling most of the permission code from the business code.

conclusion

Permissions can be designed very simple can also is very complex, the introduction of the model is just provide the basis for rights management and scheme, the most effective or from usage scenarios, the usage scenario decided to business logic and business logic decision logic function, the function of the appropriate granularity partition will contribute to the formation of flexible and efficient system of permissions.

This article is published from netease Cloud Music big front end team, the article is prohibited to be reproduced in any form without authorization. Grp.music – Fe (at) Corp.Netease.com We recruit front-end, iOS and Android all year long. If you are ready to change your job and you like cloud music, join us!