Base solution for your next web application
Starts in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

How to set permissions to menu items #2486


User avatar
0
sparta93 created

Hello, I recently discovered ASP.NET Boilerplate and it is a really amazing framework to get development started. I am trying to set up permissions for new menu items so that only the users can see certain pages and not the admins.

FYI I'm using the .NET CORE version of boilerplate.

I tried the following -

I first went to CORE\Authorization\PermissionNames.cs and added my new permission as the following:

public const string Pages_Subscriber = "Pages.Subscriber";

Then I went to CORE\Authorization\SEAAuthorizationProvider.cs and added the following:

   var subscribers = pages.CreateChildPermission(PermissionNames.Pages_Subscriber, L("Subscribers"));

Then in NavigationProvider.CS, I am adding the menu item like the following:

.AddItem( new MenuItemDefinition( "dashboard", L("dashboard"), url: "#", icon: "fa fa-home", requiredPermissionName: PermissionNames.Pages_Subscriber )

I'm still not seeing the menu item after logging into a user account I created, is there a step I'm missing. Any help will be appreciated, Thank you!


5 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    It seems like you have defined the permission correctly and set it for the menu item. But you also need to grant this permission to your user.

    You can either use a code like this

    var user = await UserManager.GetUserByIdAsync(1);
    await UserManager.SetGrantedPermissionsAsync(user, grantedPermissions)
    

    or you can do it in the Seed method of your dbcontext. You need to insert a record to AbpPermissions table. Second option might be good for granting this permission to admin role or admin user.

  • User Avatar
    0
    sparta93 created

    Thank you. This is helpful.

    I see now that I forgot to give the permission to the user.

    Where would I ideally add those 2 lines? in which file? thank you

    var user = await UserManager.GetUserByIdAsync(1); await UserManager.SetGrantedPermissionsAsync(user, grantedPermissions)

  • User Avatar
    0
    sparta93 created

    I put the following inside my PermissionChecker.cs file and it worked -

            var user = userManager.GetUserByIdAsync(3).Result;
    
            //Grant user3 subscriber permissions to view dashboard pages
            var permissions = PermissionFinder
                .GetAllPermissions(new SEAAuthorizationProvider())
                .Where(n=>n.Name.ToString()=="Pages.Subscribers")
                .ToList();
    
             userManager.SetGrantedPermissionsAsync(user, permissions);
    

    Also, I had to manually update some tables in the database. I probably have to create some functionality from the client side so assigning roles/permissions can be easier or is there a better way? thanks

  • User Avatar
    0
    sergii created

    All permissions could be defined in your custom AuthorizationProvider

    public class MyAuthorizationProvider : AuthorizationProvider
        {
            public override void SetPermissions(IPermissionDefinitionContext context)
            {
                SetPagePermissions(context);
    
                SetEntityPermissions(context);
    
                var permission = context.GetPermissionOrNull(PermissionNames.Impersonation.Name);
                if (permission == null)
                {
                    context.CreatePermission(PermissionNames.Impersonation.Name);
                }
            }
      }
    

    Also permissions should be assigned to users or roles, you can do it easely in EF Seeds:

    private Role CreateAdminRole(int? tenantId)
            {
                var adminRole = _context.Roles.Include(e => e.Permissions).FirstOrDefault(e => e.Name == StaticRoleNames.Tenants.Admin && e.TenantId == tenantId);
                if(adminRole == null)
                {
                    adminRole = _context.Roles.Add(new Role(tenantId, StaticRoleNames.Tenants.Admin, StaticRoleNames.Tenants.Admin) { IsStatic = true, IsActive = false });
                    _context.SaveChanges();
                }
    
                // Grant all permissions to admin role
                var permissions = PermissionFinder
                    .GetAllPermissions(new MyAuthorizationProvider())
                    .Where(p => p.MultiTenancySides.HasFlag(tenantId.HasValue?MultiTenancySides.Tenant: MultiTenancySides.Host))
                    .ToList();
    
                var existPermissions = adminRole.Permissions?.ToList() ?? new List<RolePermissionSetting>(0);
                if (existPermissions.Count != permissions.Count)
                {
                    foreach (var permission in permissions)
                    {
                        if (existPermissions.Any(e => e.Name == permission.Name && e.TenantId == tenantId)) continue;
    
                        AddPermissionForRole(adminRole, permission, tenantId);
                    }
                    // remove obsolete permissions
                    foreach (var permission in existPermissions)
                    {
                        if (!permissions.Any(e => e.Name == permission.Name)) {
                            _context.Permissions.Remove(permission);
                        }
                    }
    
                    _context.SaveChanges();
                }
    
                return adminRole;
            }
            private void AddPermissionForRole(Role role, Permission permission, int? tenantId)
            {
                _context.Permissions.Add(
                    new RolePermissionSetting
                    {
                        TenantId = tenantId,
                        Name = permission.Name,
                        IsGranted = true,
                        RoleId = role.Id
                    });
            }
    
  • User Avatar
    0
    ismcagdas created
    Support Team

    Thanks @Sergii,

    It is a good example :)