mo-esmp / DynamicRoleBasedAuthorizationNETCore

Dynamic Role-Based Access Control for ASP.NET Core MVC and Web API
GNU General Public License v3.0
451 stars 94 forks source link

Admin User #1

Closed gvsrini closed 6 years ago

gvsrini commented 6 years ago

This is exactly what I was looking for, but one hitch to get started - which is the Admin user? Can't seem to find where you defined it.

mo-esmp commented 6 years ago

You can create a role and check all controllers and actions and name it admin role and role can access all controllers and action then assign admin role to a user. in authorization filter you can bypass access check if user has admin controller.

var roles = await (
     from user in _dbContext.Users
     join userRole in _dbContext.UserRoles on user.Id equals userRole.UserId
     join role in _dbContext.Roles on userRole.RoleId equals role.Id
     where user.UserName == userName
     select role
).ToListAsync();

if(roles.Any(r => r.Name.ToLower() == "admin"))
    return;
gvsrini commented 6 years ago

The problem was after I added Access column in the AspNetRoles table, I had NULL values in it and I was not able to move forward.

I had to make these changes in DynamicAuthorisationFilter.cs & SecureContentTagHelper.cs:

            foreach (var role in roles)
            {
                if(role.Access == null)
                    continue;

                var accessList = JsonConvert.DeserializeObject<IEnumerable<MvcControllerInfo>>(role.Access);
                if (accessList.SelectMany(c => c.Actions).Any(a => a.Id == actionId))
                    return;
            }

This is the RoleController.cs

SelectedControllers = (role.Access == null? null:JsonConvert.DeserializeObject<IEnumerable<MvcControllerInfo>>(role.Access))