Fine-grained access control system and method based on RBAC model
By implementing a fine-grained access control system based on the RBAC model, the problem that existing access control schemes cannot independently authorize read-only and write operations is solved. This enables flexible adjustment and canary release of access configurations, ensuring the security and controllability of configuration changes.
Patent Information
- Application Number
- CN202611365338.6
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-09-04
- Publication Date
- 2026-11-17
Smart Images

Figure CN123116239A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of information security technology, and more specifically, to a fine-grained access control system and method based on the RBAC model. Background Technology
[0002] In the deployment scenario of enterprise-level multi-role application systems, the system typically covers multiple functional modules such as business operations, system configuration management, and log auditing. The operational permission requirements of different personnel for each functional module vary significantly. It is necessary to allow specific personnel to view the response data of a certain interface, while also prohibiting them from performing data change operations through the same interface.
[0003] Existing access control solutions typically embed permission rules into business logic code in a hard-coded manner, or only establish coarse-grained access control relationships between user accounts and functional modules. Although some solutions introduce the RBAC model and establish the association between users, roles and permission records, the granularity of permission entities remains at the interface path level, without further refining the authorization differences of different operation types on the same interface, and the permission verification logic is scattered in each business processing module for implementation.
[0004] The above solution has the following shortcomings: read-only and write operations on the same interface path cannot be authorized separately; query and modification behaviors must rely on two independently registered path records for separate control or be merged into the same authorization level; permission rules are coupled with business code, requiring source code modification and redeployment when role responsibilities are adjusted; and permission verification logic is repeatedly implemented in various business modules, resulting in inconsistent verification behaviors and a lack of unified unauthorized access interception methods. These shortcomings collectively lead to the technical problem of failing to meet the fine-grained read / write permission control requirements in multi-role application systems. Summary of the Invention
[0005] This invention provides a fine-grained permission control system and method based on the RBAC model, which solves the technical problems in related technologies such as insufficient granularity of permission management, inability to independently control the authorization identifiers of read-only and write operations at the interface level, and lack of version management and canary release capabilities for permission configuration changes.
[0006] This invention discloses a fine-grained access control system based on the RBAC model, comprising: The permission model construction module maintains a many-to-many relationship structure between user entities, role entities, and permission entities in the database. The permission entity includes an interface path field and two independent authorization identifier fields that control read-only operations and write operations respectively. The token generation module generates a stateless token carrying a list of role identifiers and returns it to the client after the credentials are verified. The authentication middleware verifies the signature and validity period of the stateless token in the request and injects a list of user identifiers and role identifiers into the request context. The permission verification middleware aggregates a set of permission records based on the role identifier list, performs path matching between the request path and the interface path field of the permission record, and checks the corresponding authorization identifier field according to the request method. If the verification passes, the request is forwarded to the business processor; if the verification fails, a rejection response is returned.
[0007] Furthermore, the interface path field of the permission entity supports path expressions containing wildcards; when performing path matching, the permission verification middleware converts the wildcard path expression into a regular expression and compares it with the request path; when the system starts, it precompiles the interface path field values of all permission records into regular expression objects and stores them in a memory structure with the interface path field value as the key; when a permission record changes, it updates the precompilation result of the affected record.
[0008] Furthermore, after the permission verification middleware obtains the user permission record set for the first time, it writes the set into the cache service with the user identifier as the key, and the cache validity period is consistent with the validity period of the stateless token. When the role permission association record changes, the cache key corresponding to the affected user identifier is cleared, so that subsequent requests can obtain the permission record set from the database again.
[0009] Furthermore, it also includes an audit log middleware, which runs independently of the authorization verification middleware processing chain after the authentication middleware. For all authenticated requests, after the response is completed, it constructs an audit log data object containing the user identifier, request path, request method, client address, response status code, and request time, and persists it to the audit log table via an asynchronous message queue; among which, the request time... , and All timestamps are in the millisecond range.
[0010] Furthermore, it also includes a pre-set role initialization module, which generates role records marked as system pre-set types when the system starts up and writes the association relationship between each pre-set role and its corresponding permission entry into the role permission association table in batches; for deletion requests of system pre-set type role records, the interface processing layer directly returns a rejection response and does not enter the database deletion operation stage.
[0011] Furthermore, it also includes a custom role management module, which verifies the uniqueness of role names when receiving role creation requests, and writes new role records to permission-related records in batches within the same database transaction; when receiving role permission modification requests, it deletes all existing permission-related records for the target role within the same transaction and then inserts new related records in batches; before deleting a role, it checks whether a user-related record for the target role exists in the user-role association table, and rejects the deletion operation if it exists.
[0012] Furthermore, it also includes: a permission version draft writing module, which, upon receiving a request to modify a role permission entry, writes the new permission configuration to the version record in the permission version table without overwriting the role permission association table. The version record includes a version identifier, a target role identifier, a permission association snapshot field, a version status field, and a grayscale ratio field. The initial value of the version status field is draft. A grayscale release instruction processing module, upon receiving a grayscale release instruction, verifies that the current value of the version status field of the target version record is draft. If it passes, it updates the version status field to grayscale and sets the grayscale ratio field value.
[0013] Furthermore, it also includes a grayscale distribution module, which checks whether there is a version status record in the grayscale version field among the roles held by the current user before the permission verification middleware performs path matching. If so, it performs a hash calculation on the user identifier to obtain the distribution value. ,in , For deterministic hash functions, A unique identifier for the user; when When the grayscale ratio field value is less than that of the target version record, the permission set is parsed and extracted from the permission-associated snapshot field to participate in subsequent path matching; when When the value is not less than the grayscale ratio field value, the existing permission association record is read from the role permission association table to participate in subsequent path matching.
[0014] Furthermore, it also includes: a grayscale monitoring aggregation module, which statistically analyzes the percentage of requests that generate rejection responses in the grayscale group and the control group within the observation period at fixed time intervals, and records them as follows: and ,in This represents the ratio of the number of rejected requests in the grayscale group to the total number of requests in the grayscale group. The difference in validation failure rate is calculated as the ratio of the number of rejected requests in the control group to the total number of requests in the control group. When the number of requests in both groups is not less than the minimum sample size threshold and Exceeding the preset abnormal threshold When the target version record is rolled back, the version status field is automatically updated to "rollback" and an alarm notification is generated. The full-scale activation command processing module, upon receiving a full-scale activation command, verifies that the version status field of the target version record is in grayscale and within the current statistical period. Not exceeding After the verification is successful, the content of the permission-associated snapshot field is written to the role-permission association table in the database transaction, and the version status field is updated to be fully effective. After the transaction is committed, the cache key corresponding to the affected user identifier is cleared.
[0015] This invention discloses a fine-grained access control method based on the RBAC model, comprising: Step 1: Establish a many-to-many relationship structure for user entities, role entities, and permission entities in the database. The permission entity includes an interface path field and two independent authorization identifier fields that control read-only operations and write operations respectively. Step 2: Receive user login request, generate a stateless token carrying a list of role identifiers after successful credential verification, and return it to the client; Step 3: Verify the signature and validity period of the stateless token for the request arriving at the gateway, and inject the user identifier and role identifier list into the request context; Step 4: Gather the permission record set based on the role identifier list, perform path matching between the request path and the interface path field of the permission record, and check the corresponding authorization identifier field according to the request method. If the verification passes, the request is transferred to the business processor; if the verification fails, a rejection response is returned.
[0016] The beneficial effects of this invention are as follows: This invention addresses the technical problem of traditional permission control schemes being unable to configure read and write operation authorizations at the same interface path granularity by introducing two independent Boolean fields—read-only permission identifier and management permission identifier—into the permission entity record. This achieves the technical effect of independently authorizing query and modification behaviors for the same interface without increasing the number of registered interface paths. By persistently storing all permission rules in database entity records and deploying a unified permission verification middleware at the API gateway layer, it solves the technical problems of permission rule coupling with business logic code, which necessitates source code modification and redeployment for permission changes, and inconsistent verification behaviors across modules. This achieves the technical effect of requiring only database record changes for permission configuration adjustments, with unauthorized access requests being uniformly intercepted by the gateway layer. Furthermore, by introducing a permission version draft storage structure, gray-scale traffic splitting logic based on user unique identifier hash values, and verification failure rate difference monitoring logic, it solves the technical problem of uncontrollable impact from immediate full-scale permission configuration changes. This achieves the technical effect of limiting the impact of fine-grained permission changes to a controllable subset of users before full-scale rollout and automatically triggering version rollback when abnormal indicators exceed thresholds. Attached Figure Description
[0017] Figure 1 This is a flowchart of the fine-grained access control method based on the RBAC model provided in Embodiment 1 of the present invention; Figure 2 This is a sub-flowchart of custom role management in the fine-grained access control method based on the RBAC model provided in Embodiment 1 of the present invention; Figure 3This is a sub-flowchart of JWT token generation in the fine-grained access control method based on the RBAC model provided in Embodiment 1 of the present invention; Figure 4 This is a sub-flowchart of the permission verification middleware processing in the fine-grained permission control method based on the RBAC model provided in Embodiment 1 of the present invention; Figure 5 This is a flowchart of the gray-scale release and automatic rollback method for changing fine-grained permission entries for roles provided in Embodiment 2 of the present invention; Figure 6 This is a sub-flowchart of gray-scale distribution and permission snapshot loading in the gray-scale release and automatic rollback method for changes to fine-grained permission entries for roles provided in Embodiment 2 of the present invention. Figure 7 This is a sub-flowchart of the gray-scale monitoring aggregation in the gray-scale release and automatic rollback method for changes to fine-grained permission entries for roles provided in Embodiment 2 of the present invention. Detailed Implementation
[0018] The subject matter described herein will now be discussed with reference to exemplary embodiments. It should be understood that these embodiments are discussed only to enable those skilled in the art to better understand and implement the subject matter described herein, and changes may be made to the function and arrangement of the elements discussed without departing from the scope of this specification. Various processes or components may be omitted, substituted, or added as needed in the examples. Furthermore, some features described in the examples may be combined in other examples.
[0019] Example 1 At least one embodiment of the present invention discloses a fine-grained access control system based on the RBAC model, the method of which is described below. Figures 1-4 The system includes: establishing a three-layer entity relationship model of users, roles, and permissions at the data level; using JWT stateless tokens to transmit user identity and role information at the authentication level; and deploying a unified permission verification middleware at the gateway level to perform fine-grained comparisons of read and write operations, thereby solving the above-mentioned technical problems.
[0020] This implementation runs on a server-side environment that has deployed a BAS system. The server-side environment includes a relational database (for persistent storage of permission model data), an API gateway (for uniformly receiving and routing HTTP requests), and an optional caching service (for improving the performance of permission data query).
[0021] The permission model building module is configured to generate three-tier entity records and their relationships in a relational database, forming a many-to-many relationship structure of users, roles, and permissions.
[0022] Three core entity records are generated in the relational database. The user entity (TenantUser) record contains fields for user unique identifier (user_id), login username (username), account status identifier (status), and password hash value (password_hash); the role entity (SysRole) record contains fields for role unique identifier (role_id), role name (role_name), and role type identifier (role_type); the permission entity (SysPermission) record contains fields for permission unique identifier (permission_id), associated API path (api_path), read-only permission identifier (is_view), and management permission identifier (is_manage).
[0023] The user entity and the role entity establish a many-to-many relationship through an intermediate table (user_role), storing the mapping between user_id and role_id. A user can be associated with multiple role records simultaneously, and a role record can be associated with multiple users. The role entity and the permission entity establish a many-to-many relationship through an intermediate table (role_permission), storing the mapping between role_id and permission_id. A role can be associated with multiple permission records, and a permission record can belong to multiple roles.
[0024] `is_view` and `is_manage` are two boolean fields in the permission entity, used to distinguish between read-only and write operation authorizations at the same `api_path` granularity. The `is_view` field controls whether read-only query operations are allowed for the `api_path`, corresponding to the HTTP GET method; the `is_manage` field controls whether data modification operations are allowed for the `api_path`, corresponding to the HTTP POST, PUT, PATCH, and DELETE methods. For the `api_path` associated with the same permission entity record, `is_view` and `is_manage` can have independent values, decoupling read and write operation authorizations for the same interface, eliminating the need to register two separate `api_path` records for query and modification operations of the same resource. For example, for an `api_path` of " / api / plan / ",... The permission record allows a specific role to set is_view to true and is_manage to false, so that the role can only view the list and details of test plans, but cannot create, modify or delete test plans.
[0025] The api_path field supports wildcard expressions: api_path field values can contain asterisks (...). The wildcard () is used as a path segment wildcard to express unified authorization for all interfaces under a certain functional module. By configuring a single permission record containing the wildcard for the same functional module, instead of registering permission records separately for each specific interface under that module, the number of records in the permission table is reduced, and new interfaces are automatically included in the coverage of the existing permission configuration, without the need to synchronously update the permission table data every time a new interface is added.
[0026] The preset role initialization module is configured to generate preset role records when the system starts for the first time and write the association relationship between each role and its corresponding permission entry into the role_permission association table in batches.
[0027] Pre-defined role records are generated through a database initialization script. The `role_type` field is marked as a system-predefined type, distinct from administrator-defined role records. The generated pre-defined role records cover five roles: Super Administrator, System Administrator, Security Officer, Log Auditor, and Regular User. The scope of permission entries associated with each role is as follows: Super Administrator is associated with all system permission records, with `is_view` and `is_manage` both set to true for each record; System Administrator is associated with permission records for system configuration, user management, system upgrades, and other maintenance modules (both `is_view` and `is_manage` are true), but not with write operation permission records for the security testing module; Security Officer is associated with all permission records for the security testing module (both `is_view` and `is_manage` are true), and with permission records for the system configuration and user management modules containing only records where `is_view` is true; Log Auditor is associated only with permission records for the log auditing module where `is_view` is true and `is_manage` is false; Regular User is associated only with basic view permission records, and not with any permission records involving system configuration modification, user management, or security test task execution.
[0028] Role records with the `role_type` field set to a system-predefined type are protected against deletion: when a deletion request for this type of role is received, the system directly returns an error response indicating that the operation is not allowed at the interface processing layer, without proceeding to the database deletion operation stage, thereby preventing the loss of core system roles due to accidental operation.
[0029] A custom role management module is configured to receive role creation, permission modification, and role deletion requests submitted by the administrator, and to persistently store role records and permission association records in the database to achieve data-driven management of permission configuration.
[0030] The system receives role creation requests submitted by administrators. The request data includes the role name (role_name), role description (role_desc), and a list of selected permission entry IDs (including the is_view and is_manage check status for each entry). It verifies the uniqueness of the role_name in the role table. If successful, it generates a new role record in the SysRole table, marking the role_type field as a custom type. Subsequently, it batch writes the mapping between selected permission entry IDs and new role IDs into the role_permission association table. The above role table insertion and batch write operations to the association table are performed within the same database transaction, ensuring the atomicity of the operations.
[0031] When receiving a role permission modification request submitted by an administrator, all existing associated records corresponding to the target role ID are deleted from the role_permission association table, and then the association relationships of the latest permission entries included in the request are written in batches. The above deletion and insertion operations are performed in the same transaction.
[0032] Before performing a custom role deletion operation, check if a user-associated record exists in the user_role association table corresponding to the target role ID. If an association record exists, the deletion operation is rejected and a prompt message is returned, requiring the relevant user to sever their association with the role before deletion is performed, to ensure the referential integrity of permission data.
[0033] The JWT token generation module is configured to receive user login requests, complete credential verification, generate a JWT token carrying role information, and return it to the client.
[0034] The system receives a login request from the client, containing the username and password in plaintext. It retrieves the user record from the user table based on the username. If the record does not exist, it returns an authentication failure response. If the record exists, it uses the bcrypt algorithm to perform a hash comparison between the submitted plaintext password and the password_hash field value in the user record. If the comparison fails, it returns an authentication failure response. If the comparison succeeds, it reads the status field of the user record. If the account is disabled or locked, it returns an account unavailable response.
[0035] After the above verification, the user_role association table is queried to obtain all role IDs held by the user, and the payload data of the JWT token is constructed. The payload includes the following fields: user unique identifier (sub, corresponding to user_id), login username (username), role ID list (roles, array type), token issuance time (iat, Unix timestamp), and token expiration time (exp, Unix timestamp, value is ait plus 7200, i.e., validity period of 2 hours). The payload is signed using the HS256 algorithm, and the signing key is injected into the application process as an environment variable. The generated JWT token string consists of a Base64URL encoded Header, Payload, and Signature connected by dot notations, and is returned to the client.
[0036] JWT tokens are stateless tokens, meaning the server does not need to maintain user session state records in memory or a database. After obtaining the token, the client includes it in the Authorization header of every subsequent HTTP request using the Bearer scheme, in the format "earer".<token_string> The server extracts the token string from the request header for verification during the authentication phase of the request processing flow, so that there is no need to synchronize session state data between the server processing nodes, supporting horizontally scalable deployment scenarios.
[0037] The JWT authentication middleware is configured to perform token signature verification and validity check on each HTTP request arriving at the API gateway, and inject the parsed user identity information into the request context.
[0038] Extract the token string from the Authorization request header, verify the token signature using the JWT Secret Key held by the server. If the signature does not match, return an HTTP 401 status code and terminate the request processing. After successful signature verification, check the exp field value in the payload. If the current Unix timestamp exceeds the exp value, return an HTTP 401 status code. After successful signature verification and the token has not expired, parse the user ID (user_id) and role ID list (roles) from the payload and inject them into the context object of the current request for use by subsequent middleware and business processing.
[0039] The permission verification middleware is configured to perform fine-grained read and write permission comparisons on HTTP requests that have passed authentication, after the JWT authentication middleware. If the verification passes, the request is forwarded to the business logic processor; if the verification fails, an HTTP 403 response is returned.
[0040] Read the user_id and role ID list from the request context. If the above information is missing, return an HTTP 401 status code and terminate the process.
[0041] Read the target path (request_path) and HTTP method (request_method) of the current HTTP request, and classify the HTTP method into operation types: GET methods are classified as read-only operations, corresponding to the is_view field in the permission record; POST, PUT, PATCH, and DELETE methods are classified as write operations, corresponding to the is_manage field in the permission record.
[0042] Based on the list of role IDs, query the combined result of the role_permission association table and the SysPermission permission table to obtain the complete permission record set for the user, aggregated from all roles held. Then, perform path matching on each record in the permission record set: compare the api_path field value of the record with the request_path. The matching rules support exact matching and wildcard matching. Wildcard matching will return the asterisk (*) in api_path. After being converted to a regular expression pattern, it is compared with the request_path using regular expressions. Upon finding a permission record that matches the path, the corresponding boolean flag field is checked based on the operation type of the current request: if it's a read-only operation, the is_view field is checked for truth; if it's a write operation, the is_manage field is checked for truth. The union of permission records associated with multiple roles held by the user is used for comparison; that is, if any permission record that matches the path and whose corresponding operation type flag is truth exists, the permission verification is considered successful.
[0043] If the validation passes, the middleware will forward the request to the business logic processor; if the validation fails, the middleware will return an HTTP 403 status code and a standardized response body containing the error code (PERMISSION_DENIED) and error description information to the client, the request processing flow will be terminated, and the business logic processor will not be invoked.
[0044] To reduce the frequency of database queries triggered by each request, the permission record set can be written to the cache service after the first query, using user_id as the dimension, with the cache key format "permission:user:<user_id> The cache validity period is consistent with the JWT token validity period (2 hours). When the role permission configuration changes, the system actively clears the cache key corresponding to the affected user_id, so that the next request will retrieve the latest permission record set from the database again, ensuring that the permission change takes effect in a timely manner.
[0045] To further improve the efficiency of path matching, the `api_path` field values of all permission records are pre-compiled into regular expression objects at system startup and stored in an in-memory structure. This avoids repeatedly performing the string-to-regular expression conversion operation for each request. The pre-compiled regular expression objects are indexed using the `api_path` field value as the key. During each path matching operation, the pre-compiled results are directly retrieved for matching, reducing the computational overhead of a single request. When the permission table data changes, the system re-triggers the regular expression pre-compilation process for the affected permission records, updating the in-memory index.
[0046] The audit log middleware is configured to generate audit log data objects for all authenticated HTTP requests and persist them to the audit log table (audit_log) via an asynchronous message queue.
[0047] The audit log middleware runs after the JWT authentication middleware and independently of the authorization verification middleware processing chain. It generates audit log records for all authenticated HTTP requests, including requests that fail authorization verification.
[0048] After the request is processed and a response is received, the following information is extracted from the request context and response data to construct an audit log data object: User ID (user_id), Username (username), HTTP Method (request_method), Request Path (request_path), Request Parameters (request_params, for GET requests record the query string, for POST or PUT requests record the JSON digest of the request body, and records sensitive fields such as passwords after de-identification), Client IP Address (client_ip, extracted from the X-Forwarded-For request header or the remote address of the connection), Request Start Time (start_time, millisecond-level Unix timestamp), Request End Time (end_time, millisecond-level Unix timestamp), HTTP Response Status Code (response_status), Response Summary (response_summary, the first 256 characters of the response body), and Request Duration (duration_ms). ; The unit is milliseconds. and All timestamps are millisecond-level Unix timestamps.
[0049] The aforementioned audit log data objects are encapsulated into messages and delivered to an asynchronous message queue within the system. A separate audit log consumption coroutine continuously retrieves messages from the queue and writes them to the audit log table (audit_log). During normal system shutdown, the process exits only after all pending messages in the queue have been consumed.
[0050] The audit log table (audit_log) supports searching by user name, time range (start_time), HTTP request method, request path prefix, and response status code. Search results are output as a paginated list. Users with log auditing privileges can export the search results in CSV or Excel format for offline processing in compliance auditing or security incident analysis scenarios.
[0051] This invention introduces two independent Boolean identifier fields, is_view and is_manage, into the permission entity record, thereby separating read-only and write operation authorizations at the same api_path granularity. This allows the system to authorize query and modification behaviors of the same interface separately without increasing the number of api_path registrations, overcoming the limitation of traditional coarse-grained permission models that cannot distinguish between read and write operation authorizations.
[0052] By persistently storing all permission rules in entity and association records of a relational database and deploying a unified permission verification middleware at the API gateway layer to perform comparisons, permission rules are completely decoupled from business logic code. Adjustments to permission configurations only require changes to database records, without modifying the application source code, thus eliminating the operational risks of modifying code and redeploying when permissions change.
[0053] JWT stateless tokens eliminate the need for the server to maintain distributed session state. The role ID list carried in the token payload allows the identity context of each request to be directly parsed from the token. Combined with the permission record storage in the caching layer, the frequency of database queries for permission verification is reduced to only when the cache expires or permissions change.
[0054] The audit log middleware operates independently of the permission verification process, ensuring that all authenticated requests, including unauthorized access attempts that fail permission verification, are logged, providing complete operation log data for security event tracing. Asynchronous writing decouples the persistent I / O operations of the audit log from the response process of the main business requests, allowing audit log recording operations to not block the return of responses from the main business requests.
[0055] Example 2 In the fine-grained permission control method based on the RBAC model described in Example 1, the role permission modification operation in step 3, after submission, makes the new permission configuration immediately effective for all users associated with the role by clearing the cache. In scenarios with a small system scale and a limited number of users associated with a role, this immediate effectiveness mechanism can meet the timeliness requirements of permission configuration. However, in enterprise-level BAS system deployment scenarios with a large number of users, a single core business role may be associated with hundreds of users, and changes to fine-grained permission entries frequently occur in daily operations. When an administrator introduces a configuration error when modifying the role's operation type identifier (is_view, is_manage) or resource scope identifier, such as accidentally deleting a critical operation permission identifier or mistakenly setting the is_manage of a resource path to a false value, the incorrect fine-grained permission configuration will spread to all users associated with the role during the cache invalidation process, resulting in a large-scale failure of fine-grained access control and abnormal business operations. Within the time window before the error is discovered and rolled back, the number of affected users and the scope of business interruption are uncontrollable. Existing RBAC permission control processes lack the ability to verify the correctness of fine-grained permission configurations in a small group of users before full-scale rollout.
[0056] Based on Embodiment 1, at least one embodiment of the present invention discloses a canary release and automatic rollback system for changes to fine-grained permission entries for roles. The method for executing this system is described below. Figures 5-7 The system includes: by introducing permission version draft records, gray-scale distribution logic based on user ID hashes, and monitoring logic for the difference in verification failure rate during the gray-scale period, the impact of fine-grained permission changes is limited to a controllable subset of users, and automatic interception is completed before the anomaly spreads to all users, thus solving the above-mentioned technical problems.
[0057] This implementation runs in the same server environment as Example 1, and additionally maintains a permission version table (permission_version) in the relational database to persistently store draft records of fine-grained permission configurations.
[0058] The permission version draft writing module is configured to receive requests from administrators to modify fine-grained permission entries for roles, write the new permission configuration as a version draft record to the permission_version table, and not perform an overwrite write to the role_permission associated table.
[0059] The system receives modification requests from administrators for fine-grained permission entries in the RBAC model. The request data includes the target role ID (role_id), a list of new operation type identifiers (containing the is_view and is_manage values for each permission entry), and a list of new resource scope identifiers (api_path enumeration). Instead of overwriting the role_permission association table as in Example 1, the system writes the aforementioned new fine-grained permission configuration as a permission version draft record to the permission_version table.
[0060] The version record in the permission version table contains the following fields: unique version identifier (version_id), target role ID (role_id), new fine-grained permission associated snapshot (permission_snapshot, JSON format, containing a list of operation type identifiers and a list of resource scope identifiers), version status field (version_status, enumerated values are draft, grayscale, full effect, and rolled back, with an initial write value of draft), grayscale ratio field (grayscale_ratio, initial value is 0), and creation timestamp (created_at).
[0061] Through the above processing, the new fine-grained permission configuration is stored in the permission_version table in draft form, coexisting with the existing production permission association records in the role_permission association table. This does not trigger an immediate overwrite of the existing production configuration, structurally eliminating the path for changes to immediately spread to all users.
[0062] The `permission_snapshot` field stores a new, fine-grained permission-related snapshot in JSON format. Its structure corresponds to a complete mapping between the list of permission entry IDs selected by the administrator and the `is_view` and `is_manage` checkmark statuses of each entry. It is a serialized representation of the set of `role_permission` related records expected to take effect after the change. After the version record is written, the system returns a response containing `version_id` to the administrator. The administrator can then use `version_id` to reference this draft for canary releases or discarding operations.
[0063] The grayscale release instruction processing module is configured to receive grayscale release instructions submitted by the administrator and update the version_status and grayscale_ratio fields of the target version record.
[0064] Receive the canary release command submitted by the administrator. The command data includes the target version ID (version_id) and the canary scale ratio value (grayscale_ratio_new, an integer ranging from 0 to 100, representing the percentage). Retrieve the target version record from the permission_version table, verify that its version_status field currently has a draft value; if the verification passes, update the version_status field of the target version record to the canary scale value, and update the grayscale_ratio field to the grayscale_ratio_new value specified in the command.
[0065] The `grayscale_ratio_new` value in the grayscale release command can be adjusted multiple times. Administrators can submit adjustment commands multiple times during the grayscale observation period to gradually increase the grayscale ratio from a smaller value (e.g., 10) to a larger value (e.g., 50), achieving gradual grayscale expansion. Each time an adjustment command arrives, the current value of the `version_status` field in the target version record is verified to be in grayscale. After successful verification, the `grayscale_ratio` field is updated to the new ratio value.
[0066] The grayscale splitting and permission snapshot loading module is configured to divide users into grayscale groups and control groups based on user ID hash values before path matching and operation type comparison in the permission verification middleware, and load fine-grained permission-related snapshots in the permission_snapshot field for grayscale group users.
[0067] Before the execution path matching and operation type comparison of the permission verification middleware in Example 1, the following grayscale splitting processing logic is inserted.
[0068] Read the list of user role IDs from the request context. Iterate through each role ID and check if the `permission_version` table contains a record for the target role ID with a `version_status` value that corresponds to the grayscale version. If it exists, perform a hash calculation on the current requesting user's `user_id`, and record the result as... ,in: ; in For deterministic hash functions (such as MurmurHash3 or FNV-1a). This is a unique identifier for the user, and $\bmod$ is the modulo operation. The range of values is .
[0069] Will With version history Field value comparison: If If the current requesting user is classified as a gray-scale user, a fine-grained permission-related snapshot is extracted from the permission_snapshot field of the version record. This fine-grained permission-related snapshot is used as the effective permission set for the target role in subsequent path matching and operation type comparison. If so, the current requesting user will be designated as a control group user, and the existing fine-grained permission association records of the target role will be read from the role_permission association table to participate in subsequent comparisons.
[0070] Hash function The determinism ensures that each request from the same user during the gray-scale period is assigned to the same group, avoiding inconsistencies in permission behavior due to group changes during a single session. Control group users continuously load their original production permission configurations from the role_permission association table during the gray-scale period, forming a comparison with the gray-scale group users, which is used for subsequent calculation of the failure rate difference.
[0071] The permission data for users in the grayscale group is derived from the memory parsing result of the permission_snapshot field and is not written to the cache key (permission:user:) described in Example 1.<user_id> This is to avoid contaminating the cache read results of the control group users with grayscale permission data. The cache read logic for the control group users is consistent with that in Example 1.
[0072] The grayscale monitoring aggregation module is configured to perform monitoring aggregation tasks on version records in the grayscale at fixed time intervals, calculate the difference in verification failure rate between the grayscale group and the control group, and automatically update the version status to "rollback" and generate an alarm notification when the difference exceeds the abnormal threshold.
[0073] For version records in the `permission_version` table where the `version_status` field value is in the grayscale version, execute a grayscale monitoring aggregation task at fixed time intervals. The aggregation task retrieves permission verification request records related to the target role from the audit log table (`audit_log`) within the grayscale observation period. Based on the grayscale grouping identifier (according to the hash grouping results, a grayscale group or control group label is appended to the audit log record), it calculates the percentage of requests that generated HTTP 403 responses during the permission verification phase for each of the two user groups, denoted as follows: (Grayscale group validation failure rate) and (Failure rate of control group validation).
[0074] Calculate the difference in verification failure rates between the two groups. : ; in The ratio of requests that generated 403 responses for permission verification for users in the grayscale group during the statistical period to the total number of requests in the grayscale group. This represents the ratio of the number of requests from the control group that resulted in a 403 response for permission verification to the total number of requests from the control group within the same statistical period. The range of values is .
[0075] like Exceeding the preset abnormal threshold (Right now If the grayscale version has an abnormal configuration, the system will automatically update the `version_status` field of that version record to "rolled back" and generate an alarm notification to push to the administrator. The alarm content includes `version_id`, Value and trigger time.
[0076] A value greater than zero indicates that the failure rate of fine-grained permission verification for users in the grayscale group is higher than that in the control group. This means that the new fine-grained permission configuration triggered more access denial responses than the existing configuration, serving as a quantitative detection signal for configuration errors (such as accidental deletion of operation permission identifiers). Abnormal threshold. Pre-configured by the system administrator based on business scenarios, this distinguishes between normal permission tightening adjustments and abnormal configuration errors. Only when... Automatic rollback is triggered when necessary to prevent reasonable permission tightening changes from being misjudged as configuration errors.
[0077] To improve and The reliability of the statistical results is ensured by ensuring that the number of requested samples in both the grayscale group and the control group for the aggregation task is not less than the minimum sample size threshold. (Configured by the system) Difference calculation and threshold comparison are only performed when the sample size is insufficient. If the sample size is insufficient, only the current statistical intermediate result is recorded, and aggregation continues after the sample is supplemented in the next statistical period to avoid errors due to insufficient sample size. Excessive fluctuations caused an erroneous rollback.
[0078] The full-scale activation command processing module is configured to receive full-scale activation commands submitted by the administrator. After completing version status and difference verification, it writes the fine-grained permission-related snapshot in permission_snapshot to the role_permission association table and clears the cache keys of affected users.
[0079] Receive the full activation command submitted by the administrator. The command data includes the target version ID (version_id). Retrieve the target version record from the permission_version table, verify that its version_status field is currently in grayscale, and verify that the target version is within the current grayscale statistical period. Not exceeding the abnormal threshold After all the above verifications pass, perform the following operations in the database transaction: delete all existing fine-grained permission association records corresponding to the target role ID (role_id) from the role_permission association table; parse and restore the fine-grained permission association snapshot stored in the permission_snapshot field of the target version record to the standard association record format, and batch insert them into the role_permission association table; update the version_status field of the target version record to be fully effective.
[0080] After the transaction is successfully committed, batch clear all cache keys (permission:user:) corresponding to the target role in the cache service described in Example 1.<user_id> This ensures that all users reload fine-grained permission records from the updated role_permission association table on their next request. The cache clearing operation is performed after a successful transaction commit to ensure consistency between the role_permission association table data and the cached data.
[0081] The rollback processing module is configured to update the version_status field of the target version record to "rollback has been completed" when receiving a manual rollback command or when an automatic rollback is triggered by the grayscale monitoring aggregation module, clear the grayscale group user cache key, and generate a rollback audit log record.
[0082] When receiving a rollback command manually submitted by the administrator, or when a rollback is triggered by the grayscale monitoring aggregation module, the target version record is retrieved from the permission_version table, its version_status field is updated to indicate that it has been rolled back, and the grayscale_ratio field is reset to 0.
[0083] Clear gray group users (i.e.) The cache key corresponding to the user (permission:user:)<user_id> This causes users in the grayscale group to be redirected to the control group processing path when they make their next request because the target role no longer has a version_status record in the grayscale. The existing fine-grained permission association records are read from the role_permission association table to participate in the permission comparison, and the production permission configuration before the change is restored.
[0084] Based on the asynchronous audit log writing process in Implementation Example 1, a rollback audit log record is generated and delivered to the asynchronous message queue. The log content includes version_id, target role ID (role_id), rollback trigger reason (enumerated value: manual or automatic), and trigger time. Value (recorded during automatic rollback to trigger threshold comparison) The actual value is recorded during manual rollback, representing the most recent statistical period. The value) and the number of affected grayscale users (taken from the group statistics).
[0085] This invention introduces a permission_version table to store draft versions of fine-grained permission configurations. This allows changes to role permission entries to coexist in draft form with the existing production configuration in the role_permission association table before taking full effect, without triggering an immediate overwrite of the existing configuration. This eliminates the immediate propagation path of fine-grained permission changes to all users at the data structure level, overcoming the structural constraint in Implementation 1 where permission modification operations and cache clearing are linked, causing changes to take full effect immediately.
[0086] based on The hash-based traffic splitting logic utilizes the determinism and uniformity of hash functions to stably divide users under the same role into a gray-scale group and a control group. During the gray-scale period, each request from the same user belongs to the same group, ensuring the consistency of permission behavior during the gray-scale period, while limiting the impact of configuration errors within the gray-scale ratio range.
[0087] The difference in fine-grained permission verification failure rate between the grayscale group and the control group was calculated. This transforms the abnormal access denial phenomenon caused by fine-grained permission configuration errors (such as accidental deletion of operation type identifiers) into quantifiable and comparable monitoring indicators. When Exceeding the threshold It automatically updates the version status to "rollback" and automatically intercepts configuration errors before they spread to all users, thus solving the problem that the existing RBAC permission control process lacks a mechanism to verify the correctness of fine-grained permission configurations in a small group of users.
[0088] The rollback operation clears the cache of users in the grayscale group and updates the version status to "rollbacked". This allows users in the grayscale group to automatically switch to the control group processing path on the next request and restore the original production permission configuration in the role_permission association table. The rollback process does not require write operations to the role_permission association table, which reduces the scope of database changes in the rollback operation and reduces the possibility of introducing additional data consistency risks.
[0089] The embodiments of the present invention have been described above. However, the embodiments are not limited to the specific implementation methods described above. The specific implementation methods described above are merely illustrative and not restrictive. Those skilled in the art can make more equivalent embodiments under the guidance of the present embodiments, and all of them are within the protection scope of the present embodiments.
Claims
1. A fine-grained access control system based on the RBAC model, characterized in that, include: The permission model construction module maintains a many-to-many relationship structure between user entities, role entities, and permission entities in the database. The permission entity includes an interface path field and two independent authorization identifier fields that control read-only operations and write operations respectively. The token generation module generates a stateless token carrying a list of role identifiers and returns it to the client after the credentials are verified. The authentication middleware verifies the signature and validity period of the stateless token in the request and injects a list of user identifiers and role identifiers into the request context. The permission verification middleware aggregates a set of permission records based on the role identifier list, performs path matching between the request path and the interface path field of the permission record, and checks the corresponding authorization identifier field according to the request method. If the verification passes, the request is forwarded to the business processor; if the verification fails, a rejection response is returned.
2. The fine-grained access control system based on the RBAC model according to claim 1, characterized in that, The interface path field of the permission entity supports path expressions containing wildcards; when performing path matching, the permission verification middleware converts the wildcard path expression into a regular expression and compares it with the request path; when the system starts, it precompiles the interface path field values of all permission records into regular expression objects and stores them in a memory structure with the interface path field value as the key; when a permission record changes, it updates the precompilation result of the affected record.
3. The fine-grained access control system based on the RBAC model according to claim 1, characterized in that, After obtaining the user permission record set for the first time, the permission verification middleware writes the set into the cache service with the user identifier as the key, and the cache validity period is consistent with the stateless token validity period. When a role permission association record changes, the cache key corresponding to the affected user's identifier is cleared, so that subsequent requests can retrieve the permission record set from the database again.
4. The fine-grained access control system based on the RBAC model according to claim 1, characterized in that, It also includes an audit log middleware, which runs independently of the authorization verification middleware processing chain after the authentication middleware. For all authenticated requests, after the response is completed, it constructs an audit log data object containing the user identifier, request path, request method, client address, response status code, and request time, and persists it to the audit log table via an asynchronous message queue; among which, the request time... , and All timestamps are in the millisecond range.
5. The fine-grained access control system based on the RBAC model according to claim 1, characterized in that, It also includes a pre-set role initialization module, which generates role records marked as system pre-set types when the system starts up and writes the association relationship between each pre-set role and its corresponding permission entry into the role permission association table in batches; for deletion requests of system pre-set type role records, the interface processing layer directly returns a rejection response and does not enter the database deletion operation stage.
6. The fine-grained access control system based on the RBAC model according to claim 1, characterized in that, It also includes a custom role management module, which verifies the uniqueness of role names when receiving role creation requests, and writes new role records to permission-related records in batches within the same database transaction; When receiving a request to modify role permissions, delete all existing permission-related records for the target role within the same transaction and then insert new related records in batches. Before deleting a role, check if there is a user-associated record for the target role in the user-role association table. If so, refuse the deletion operation.
7. The fine-grained access control system based on the RBAC model according to any one of claims 1 to 6, characterized in that, It also includes: a permission version draft writing module, which, when receiving a request to modify a role permission entry, writes the new permission configuration to the version record in the permission version table without overwriting the role permission association table. The version record contains a version identifier, target role identifier, permission association snapshot field, version status field, and grayscale ratio field. The initial value of the version status field is draft; and a grayscale release instruction processing module, which, when receiving a grayscale release instruction, verifies that the current value of the version status field of the target version record is draft. If it passes, it updates the version status field to grayscale and sets the grayscale ratio field value.
8. The fine-grained access control system based on the RBAC model according to claim 7, characterized in that, It also includes a grayscale splitting module, which checks whether there is a version status record in the grayscale version of the current user's roles before the permission verification middleware performs path matching. If so, it performs a hash calculation on the user identifier to obtain the splitting value. ,in , For deterministic hash functions, A unique identifier for the user; when When the grayscale ratio field value is less than that of the target version record, the permission set is parsed and extracted from the permission-associated snapshot field to participate in subsequent path matching; when When the value is not less than the grayscale ratio field value, the existing permission association record is read from the role permission association table to participate in subsequent path matching.
9. The fine-grained access control system based on the RBAC model according to claim 8, characterized in that, Also includes: The grayscale monitoring aggregation module statistically analyzes the percentage of rejected requests generated by the grayscale group and the control group within a fixed time interval during the observation period, and records them as follows: and ,in This represents the ratio of the number of rejected requests in the grayscale group to the total number of requests in the grayscale group. The difference in validation failure rate is calculated as the ratio of the number of rejected requests in the control group to the total number of requests in the control group. When the number of requests in both groups is not less than the minimum sample size threshold and Exceeding the preset abnormal threshold When the target version record is rolled back, the version status field is automatically updated to "rollback" and an alarm notification is generated. The full-scale activation command processing module, upon receiving a full-scale activation command, verifies that the version status field of the target version record is in grayscale and within the current statistical period. Not exceeding After the verification is successful, the content of the permission-associated snapshot field is written to the role-permission association table in the database transaction, and the version status field is updated to be fully effective. After the transaction is committed, the cache key corresponding to the affected user identifier is cleared.
10. A fine-grained access control method based on the RBAC model, used to execute the fine-grained access control system based on the RBAC model as described in any one of claims 1 to 9, characterized in that, include: Step 1: Establish a many-to-many relationship structure for user entities, role entities, and permission entities in the database. The permission entity includes an interface path field and two independent authorization identifier fields that control read-only operations and write operations respectively. Step 2: Receive user login request, generate a stateless token carrying a list of role identifiers after successful credential verification, and return it to the client; Step 3: Verify the signature and validity period of the stateless token for the request arriving at the gateway, and inject the user identifier and role identifier list into the request context; Step 4: Gather the permission record set based on the role identifier list, perform path matching between the request path and the interface path field of the permission record, and check the corresponding authorization identifier field according to the request method. If the verification passes, the request is transferred to the business processor; if the verification fails, a rejection response is returned.
