Base solution for your next web application
Open Closed

Dynamic Permission #12245


User avatar
0
[email protected] created

Hi @oguzhanagir ,

We are using Asp.net Zero V 13.3.0 with.NET Core and Angular.

We have created a dynamic permission and assigned it to a role. However, we are facing an issue where we need to retrieve data from the AbpPermissions SQL table. We attempted to implement the repository pattern, but we are unable to create a repository for the AbpPermissions table. How can we retrieve records from the AbpPermissions table?

here We have created dynamic company permissions that are not defined in the AppPermissions.cs file but have been assigned to the Admin role. These permissions have been inserted as records into the AbpPermissions table, and we want to retrieve those records.


20 Answer(s)
  • User Avatar
    0
    [email protected] created

    Hi @oguzhanagir,

    Could You please any update?

  • User Avatar
    0
    m.aliozkaya created
    Support Team

    Hi @[email protected],

    Could you check PermissionManager?

    https://aspnetboilerplate.com/Pages/Documents/Zero/Permission-Management#role-permissions

  • User Avatar
    0
    [email protected] created

    Hi @[email protected],

    Could you check PermissionManager?

    https://aspnetboilerplate.com/Pages/Documents/Zero/Permission-Management#role-permissions

    we want to get Role wise Permission AbpPermission Table record .but here not getting records.

    User role we have assigned company Permisison.AbpPermission table records is there but not got here .

  • User Avatar
    0
    [email protected] created

    Hi , this is my code i have created dynamic Permission

    public static class PermissionManagerExtensions
    {
        /// <summary>
        /// Gets all permissions by names.
        /// Throws <see cref="AbpValidationException"/> if can not find any of the permission names.
        /// </summary>
        ///        
        public static IEnumerable<Permission> GetPermissionsFromNamesByValidating(this IPermissionManager permissionManager, IEnumerable<string> permissionNames, IRepository<ModulePermission, long> modulePermissionRepository)
        {
            var permissions = new List<Permission>();
            var undefinedPermissionNames = new List<string>();
    
          var staticPermissionNames = modulePermissionRepository.GetAll()
          .Select(mp => mp.Name)
          .ToList();
    
            foreach (var permissionName in permissionNames) 
            {
                Permission permission = null;
                if (staticPermissionNames.Contains(permissionName))
                {
                    // Optionally, create a Permission object for static permissions
                    permission = new Permission(permissionName); // Adjust based on your Permission class
                }
                else
                {
                    // Check with permissionManager
                    permission = permissionManager.GetPermissionOrNull(permissionName);
                }
                if (permission != null)
                {
                    permissions.Add(permission);
                }
                else
                {
                    undefinedPermissionNames.Add(permissionName);
                }
            }
    
            if (undefinedPermissionNames.Count > 0)
            {
                throw new AbpValidationException($"There are {undefinedPermissionNames.Count} undefined permission names.")
                      {
                          ValidationErrors = undefinedPermissionNames.Select(permissionName => new ValidationResult("Undefined permission: " + permissionName)).ToList()
                      };
            }
    
            return permissions;
        }
    }
    
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    Do you get these records when you restart your app ?

  • User Avatar
    0
    [email protected] created

    Hi,

    Do you get these records when you restart your app ?

    Yes.

  • User Avatar
    0
    ismcagdas created
    Support Team

    Thanks. Could you share where do you use PermissionManagerExtensions ? I assume it is used inside a code block which uses caching.

  • User Avatar
    0
    [email protected] created

    Thanks. Could you share where do you use PermissionManagerExtensions ? I assume it is used inside a code block which uses caching.

  • User Avatar
    0
    [email protected] created

    Hi ismcagdas,

    my issue is i want to get records for role Admin,user etc form Abppermisison table. how to get all records from abpPermission table.

  • User Avatar
    0
    [email protected] created

    Thanks. Could you share where do you use PermissionManagerExtensions ? I assume it is used inside a code block which uses caching.

    any update ?

  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi

    Have you tried retrieving the data in AbpPermissions in this way?

     var permissions = PermissionManager.GetAllPermissions();
    
  • User Avatar
    0
    [email protected] created

    /// <summary> /// Application's authorization provider. /// Defines permissions for the application. /// See <see cref="AppPermissions"/> for all permission names. /// </summary> public class AppAuthorizationProvider : AuthorizationProvider { private readonly bool _isMultiTenancyEnabled; private readonly IRepository<ModulePermission, long> _modulePermissionRepository; private readonly IUnitOfWorkManager _unitOfWorkManager;

     public AppAuthorizationProvider(
         bool isMultiTenancyEnabled,
         IRepository&lt;ModulePermission, long&gt; modulePermissionRepository,
         IUnitOfWorkManager unitOfWorkManager)
     {
         _isMultiTenancyEnabled = isMultiTenancyEnabled;
         _modulePermissionRepository = modulePermissionRepository;
         _unitOfWorkManager = unitOfWorkManager;
     }
    
     public AppAuthorizationProvider(
         IRepository&lt;ModulePermission, long&gt; modulePermissionRepository,
        IMultiTenancyConfig multiTenancyConfig,           
        IUnitOfWorkManager unitOfWorkManager)
     {
         _unitOfWorkManager = unitOfWorkManager;
         _isMultiTenancyEnabled = multiTenancyConfig.IsEnabled;
         _modulePermissionRepository = modulePermissionRepository;
     }
    
     public override void SetPermissions(IPermissionDefinitionContext context)
     {
         // Static permissions defined in code
         var pages = context.GetPermissionOrNull(AppPermissions.Pages) ?? context.CreatePermission(AppPermissions.Pages, L("Pages"));
         SetStaticPermissions(pages, context);
    
         // Dynamic permissions from the database
         RegisterDynamicPermissions(context, pages);
     }
    
     private void SetStaticPermissions(Permission pages, IPermissionDefinitionContext context)
     {
         pages.CreateChildPermission(AppPermissions.Pages_DemoUiComponents, L("DemoUiComponents"));
    
         var administration = pages.CreateChildPermission(AppPermissions.Pages_Administration, L("Administration"));
    
         var roles = administration.CreateChildPermission(AppPermissions.Pages_Administration_Roles, L("Roles"));
         roles.CreateChildPermission(AppPermissions.Pages_Administration_Roles_Create, L("CreatingNewRole"));
         roles.CreateChildPermission(AppPermissions.Pages_Administration_Roles_Edit, L("EditingRole"));
         roles.CreateChildPermission(AppPermissions.Pages_Administration_Roles_Delete, L("DeletingRole"));
    
         var users = administration.CreateChildPermission(AppPermissions.Pages_Administration_Users, L("Users"));
         users.CreateChildPermission(AppPermissions.Pages_Administration_Users_Create, L("CreatingNewUser"));
         users.CreateChildPermission(AppPermissions.Pages_Administration_Users_Edit, L("EditingUser"));
         users.CreateChildPermission(AppPermissions.Pages_Administration_Users_Delete, L("DeletingUser"));
         users.CreateChildPermission(AppPermissions.Pages_Administration_Users_ChangePermissions, L("ChangingPermissions"));
         users.CreateChildPermission(AppPermissions.Pages_Administration_Users_Impersonation, L("LoginForUsers"));
         users.CreateChildPermission(AppPermissions.Pages_Administration_Users_Unlock, L("Unlock"));
         users.CreateChildPermission(AppPermissions.Pages_Administration_Users_ChangeProfilePicture, L("UpdateUsersProfilePicture"));
    
         var languages = administration.CreateChildPermission(AppPermissions.Pages_Administration_Languages, L("Languages"));
         languages.CreateChildPermission(AppPermissions.Pages_Administration_Languages_Create, L("CreatingNewLanguage"), multiTenancySides: _isMultiTenancyEnabled ? MultiTenancySides.Host : MultiTenancySides.Tenant);
         languages.CreateChildPermission(AppPermissions.Pages_Administration_Languages_Edit, L("EditingLanguage"), multiTenancySides: _isMultiTenancyEnabled ? MultiTenancySides.Host : MultiTenancySides.Tenant);
         languages.CreateChildPermission(AppPermissions.Pages_Administration_Languages_Delete, L("DeletingLanguages"), multiTenancySides: _isMultiTenancyEnabled ? MultiTenancySides.Host : MultiTenancySides.Tenant);
         languages.CreateChildPermission(AppPermissions.Pages_Administration_Languages_ChangeTexts, L("ChangingTexts"));
         languages.CreateChildPermission(AppPermissions.Pages_Administration_Languages_ChangeDefaultLanguage, L("ChangeDefaultLanguage"));
    
         administration.CreateChildPermission(AppPermissions.Pages_Administration_AuditLogs, L("AuditLogs"));
    
         var organizationUnits = administration.CreateChildPermission(AppPermissions.Pages_Administration_OrganizationUnits, L("OrganizationUnits"));
         organizationUnits.CreateChildPermission(AppPermissions.Pages_Administration_OrganizationUnits_ManageOrganizationTree, L("ManagingOrganizationTree"));
         organizationUnits.CreateChildPermission(AppPermissions.Pages_Administration_OrganizationUnits_ManageMembers, L("ManagingMembers"));
         organizationUnits.CreateChildPermission(AppPermissions.Pages_Administration_OrganizationUnits_ManageRoles, L("ManagingRoles"));
    
         administration.CreateChildPermission(AppPermissions.Pages_Administration_UiCustomization, L("VisualSettings"));
    
         var webhooks = administration.CreateChildPermission(AppPermissions.Pages_Administration_WebhookSubscription, L("Webhooks"));
         webhooks.CreateChildPermission(AppPermissions.Pages_Administration_WebhookSubscription_Create, L("CreatingWebhooks"));
         webhooks.CreateChildPermission(AppPermissions.Pages_Administration_WebhookSubscription_Edit, L("EditingWebhooks"));
         webhooks.CreateChildPermission(AppPermissions.Pages_Administration_WebhookSubscription_ChangeActivity, L("ChangingWebhookActivity"));
         webhooks.CreateChildPermission(AppPermissions.Pages_Administration_WebhookSubscription_Detail, L("DetailingSubscription"));
         webhooks.CreateChildPermission(AppPermissions.Pages_Administration_Webhook_ListSendAttempts, L("ListingSendAttempts"));
         webhooks.CreateChildPermission(AppPermissions.Pages_Administration_Webhook_ResendWebhook, L("ResendingWebhook"));
    
         var dynamicProperties = administration.CreateChildPermission(AppPermissions.Pages_Administration_DynamicProperties, L("DynamicProperties"));
         dynamicProperties.CreateChildPermission(AppPermissions.Pages_Administration_DynamicProperties_Create, L("CreatingDynamicProperties"));
         dynamicProperties.CreateChildPermission(AppPermissions.Pages_Administration_DynamicProperties_Edit, L("EditingDynamicProperties"));
         dynamicProperties.CreateChildPermission(AppPermissions.Pages_Administration_DynamicProperties_Delete, L("DeletingDynamicProperties"));
    
         var dynamicPropertyValues = dynamicProperties.CreateChildPermission(AppPermissions.Pages_Administration_DynamicPropertyValue, L("DynamicPropertyValue"));
         dynamicPropertyValues.CreateChildPermission(AppPermissions.Pages_Administration_DynamicPropertyValue_Create, L("CreatingDynamicPropertyValue"));
         dynamicPropertyValues.CreateChildPermission(AppPermissions.Pages_Administration_DynamicPropertyValue_Edit, L("EditingDynamicPropertyValue"));
         dynamicPropertyValues.CreateChildPermission(AppPermissions.Pages_Administration_DynamicPropertyValue_Delete, L("DeletingDynamicPropertyValue"));
    
         var dynamicEntityProperties = dynamicProperties.CreateChildPermission(AppPermissions.Pages_Administration_DynamicEntityProperties, L("DynamicEntityProperties"));
         dynamicEntityProperties.CreateChildPermission(AppPermissions.Pages_Administration_DynamicEntityProperties_Create, L("CreatingDynamicEntityProperties"));
         dynamicEntityProperties.CreateChildPermission(AppPermissions.Pages_Administration_DynamicEntityProperties_Edit, L("EditingDynamicEntityProperties"));
         dynamicEntityProperties.CreateChildPermission(AppPermissions.Pages_Administration_DynamicEntityProperties_Delete, L("DeletingDynamicEntityProperties"));
    
         var dynamicEntityPropertyValues = dynamicProperties.CreateChildPermission(AppPermissions.Pages_Administration_DynamicEntityPropertyValue, L("EntityDynamicPropertyValue"));
         dynamicEntityPropertyValues.CreateChildPermission(AppPermissions.Pages_Administration_DynamicEntityPropertyValue_Create, L("CreatingDynamicEntityPropertyValue"));
         dynamicEntityPropertyValues.CreateChildPermission(AppPermissions.Pages_Administration_DynamicEntityPropertyValue_Edit, L("EditingDynamicEntityPropertyValue"));
         dynamicEntityPropertyValues.CreateChildPermission(AppPermissions.Pages_Administration_DynamicEntityPropertyValue_Delete, L("DeletingDynamicEntityPropertyValue"));
    
         var massNotification = administration.CreateChildPermission(AppPermissions.Pages_Administration_MassNotification, L("MassNotifications"));
         massNotification.CreateChildPermission(AppPermissions.Pages_Administration_MassNotification_Create, L("MassNotificationCreate"));
    
         administration.CreateChildPermission(AppPermissions.Pages_Administration_EntityChanges_FullHistory, L("EntityChanges_FullHistory"));
    
         //TENANT-SPECIFIC PERMISSIONS
    
         pages.CreateChildPermission(AppPermissions.Pages_Tenant_Dashboard, L("Dashboard"), multiTenancySides: MultiTenancySides.Tenant);
    
         administration.CreateChildPermission(AppPermissions.Pages_Administration_Tenant_Settings, L("Settings"), multiTenancySides: MultiTenancySides.Tenant);
         administration.CreateChildPermission(AppPermissions.Pages_Administration_Tenant_SubscriptionManagement, L("Subscription"), multiTenancySides: MultiTenancySides.Tenant);
    
         //HOST-SPECIFIC PERMISSIONS
    
         var editions = pages.CreateChildPermission(AppPermissions.Pages_Editions, L("Editions"), multiTenancySides: MultiTenancySides.Host);
         editions.CreateChildPermission(AppPermissions.Pages_Editions_Create, L("CreatingNewEdition"), multiTenancySides: MultiTenancySides.Host);
         editions.CreateChildPermission(AppPermissions.Pages_Editions_Edit, L("EditingEdition"), multiTenancySides: MultiTenancySides.Host);
         editions.CreateChildPermission(AppPermissions.Pages_Editions_Delete, L("DeletingEdition"), multiTenancySides: MultiTenancySides.Host);
         editions.CreateChildPermission(AppPermissions.Pages_Editions_MoveTenantsToAnotherEdition, L("MoveTenantsToAnotherEdition"), multiTenancySides: MultiTenancySides.Host);
    
         var tenants = pages.CreateChildPermission(AppPermissions.Pages_Tenants, L("Tenants"), multiTenancySides: MultiTenancySides.Host);
         tenants.CreateChildPermission(AppPermissions.Pages_Tenants_Create, L("CreatingNewTenant"), multiTenancySides: MultiTenancySides.Host);
         tenants.CreateChildPermission(AppPermissions.Pages_Tenants_Edit, L("EditingTenant"), multiTenancySides: MultiTenancySides.Host);
         tenants.CreateChildPermission(AppPermissions.Pages_Tenants_ChangeFeatures, L("ChangingFeatures"), multiTenancySides: MultiTenancySides.Host);
         tenants.CreateChildPermission(AppPermissions.Pages_Tenants_Delete, L("DeletingTenant"), multiTenancySides: MultiTenancySides.Host);
         tenants.CreateChildPermission(AppPermissions.Pages_Tenants_Impersonation, L("LoginForTenants"), multiTenancySides: MultiTenancySides.Host);
    
         administration.CreateChildPermission(AppPermissions.Pages_Administration_Host_Settings, L("Settings"), multiTenancySides: MultiTenancySides.Host);
    
         var maintenance = administration.CreateChildPermission(AppPermissions.Pages_Administration_Host_Maintenance, L("Maintenance"), multiTenancySides: _isMultiTenancyEnabled ? MultiTenancySides.Host : MultiTenancySides.Tenant);
         maintenance.CreateChildPermission(AppPermissions.Pages_Administration_NewVersion_Create, L("SendNewVersionNotification"));
    
         administration.CreateChildPermission(AppPermissions.Pages_Administration_HangfireDashboard, L("HangfireDashboard"), multiTenancySides: _isMultiTenancyEnabled ? MultiTenancySides.Host : MultiTenancySides.Tenant);
         administration.CreateChildPermission(AppPermissions.Pages_Administration_Host_Dashboard, L("Dashboard"), multiTenancySides: MultiTenancySides.Host);
    
         // Add other static permissions here...
     }
    
     private void RegisterDynamicPermissions(IPermissionDefinitionContext context, Permission rootPermission)
     {
         using (var uow = _unitOfWorkManager.Begin())
         {
             // Fetch all dynamic permissions from the database
             var modulePermissions = _modulePermissionRepository.GetAll().IgnoreQueryFilters();
    
             var modulePermissionsList = modulePermissions.ToList(); // Materialize the query
    
             foreach (var modulePermission in modulePermissionsList.Where(mp => string.IsNullOrEmpty(mp.ParentName)))
             {
                 // Top-level permission
                 var parentPermission = rootPermission.CreateChildPermission(
                     modulePermission.Name,
                     new FixedLocalizableString(modulePermission.DisplayName ?? modulePermission.Name),
                     modulePermission.Description != null ? new FixedLocalizableString(modulePermission.Description) : null,
                     _isMultiTenancyEnabled ? MultiTenancySides.Host | MultiTenancySides.Tenant : MultiTenancySides.Tenant
                 );
    
                 // Add child permissions recursively
                 AddChildPermissions(parentPermission, modulePermissionsList, modulePermission.Name);
             }              
             uow.Complete(); // Complete the unit of work
         }
     }
    
     private void AddChildPermissions(Permission parentPermission, List&lt;ModulePermission&gt; modulePermissions, string parentName)
     {
         var childPermissions = modulePermissions.Where(mp => mp.ParentName == parentName).ToList();
    
         foreach (var childPermission in childPermissions)
         {
             var createdChild = parentPermission.CreateChildPermission(
                 childPermission.Name,
                 new FixedLocalizableString(childPermission.DisplayName ?? childPermission.Name),
                 childPermission.Description != null ? new FixedLocalizableString(childPermission.Description) : null,
                 _isMultiTenancyEnabled ? MultiTenancySides.Host | MultiTenancySides.Tenant : MultiTenancySides.Tenant
             );
    
             // Recursively add children of the current child
             AddChildPermissions(createdChild, modulePermissions, childPermission.Name);
         }
     }
     private static ILocalizableString L(string name)
     {
         return new LocalizableString(name, DemoConsts.LocalizationSourceName);
     }
    
    
     public void RefreshPermissions(IPermissionDefinitionContext context)
     {
         var pages = context.GetPermissionOrNull(AppPermissions.Pages);
         if (pages == null)
         {
             throw new AbpException("Root permission 'Pages' not found.");
         }
    
         RegisterDynamicPermissions(context, pages);
     }
    

    } How can I ensure that the newly added permissions at runtime are retrieved when I call var permissions = PermissionManager.GetAllPermissions();? Currently, it does not return the newly created permissions.

    In my application, permissions are loaded once during initialization, including both static and module-specific permissions. However, when a new permission is added dynamically at runtime, the PermissionManager.GetAllPermissions() method does not seem to reflect this update. I suspect that the method may be using a cached or static list of permissions. I need guidance on how to ensure that the method returns all permissions, including those added at runtime. Should I explicitly refresh or reload the permissions, or is there a recommended approach to handle this scenario?

  • User Avatar
    0
    [email protected] created

    HI @oguzhanagir, any Update Please?

  • User Avatar
    0
    m.aliozkaya created
    Support Team

    Hi @[email protected],

    We are planning to create a blog post about dynamic permissions. Please stay tuned.

  • User Avatar
    0
    [email protected] created

    Hi @[email protected],

    We are planning to create a blog post about dynamic permissions. Please stay tuned.

    any update?

  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi

    We have created an issue for this, you can follow the developments from here. Enjoy your work

  • User Avatar
    0
    [email protected] created

    Hi

    We have created an issue for this, you can follow the developments from here. Enjoy your work

    any documentation?

  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi

    Dynamic Permissions blog post merged will soon be published on the ASP.NET Zero website. You can review the blog post created from the pull request here.

  • User Avatar
    0
    [email protected] created

    Hi

    Dynamic Permissions blog post merged will soon be published on the ASP.NET Zero website. You can review the blog post created from the pull request here.

    Is this feature available in ASP.NET Core with Angular version 14.0.0?

  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi

    This feature is not available in the latest version. The blog post has been added with explanations on how to add this feature. At the same time, a sample project containing this feature has been added.