Create & Toggle User Roles In ASP.NET Core Identity

Published on

Over the last couple of weeks I've shown you how to reset passwords in ASP.NET Identity, and then how to lock & unlock users.

This week we will be building upon that code to enable the ability to create new user roles, and then toggles those roles on individual users.

We will then apply filtering to individual controllers on your ASP.NET application so that only users with a specific role can access a page or area.

This can be extremely useful if you need to give limit access to cirtain areas of your web application. Maybe you have an admin area of your website that only administrators can access. Or maybe you have an area where only team leaders can manage users within the team and create new users.

The Code Example

Here is the code you will need to create new roles, and toggle the roles that are assigned to a user.

    public interface IUsers
    {
        public void CreateRole(string roleName);
        public void ToggleUserRole(string userId, string roleId);
        public string GetRoleIdByName(string name);
    }

    public class Users : IUsers
    {
        #region Constructor
        private readonly RoleManager<IdentityRole> _roleManager;
        private readonly UserManager<IdentityUser> _userManager;
        public Users(RoleManager<IdentityRole> roleMgr, UserManager<IdentityUser> userMgr)
        {
            _roleManager = roleMgr;
            _userManager = userMgr;
        }
        #endregion

        public void CreateRole(string roleName)
        {
            if (!string.IsNullOrWhiteSpace(roleName))
            {
                var task = _roleManager.CreateAsync(new IdentityRole(roleName));
                task.Wait();
            }
        }

        public void ToggleUserRole(string userId, string roleId)
        {
            if (string.IsNullOrEmpty(userId)) return;
            if (string.IsNullOrEmpty(roleId)) return;

            var userTask = _userManager.FindByIdAsync(userId);
            userTask.Wait();
            var user = userTask.Result;

            var roleTask = _roleManager.FindByIdAsync(roleId);
            roleTask.Wait();
            var role = roleTask.Result;

            var getRolesTask = _userManager.GetRolesAsync(user);
            getRolesTask.Wait();
            var rolesForUser = getRolesTask.Result;

            bool shouldEnable = true;
            foreach (var item in rolesForUser)
            {
                if (item == role.Name)
                {
                    shouldEnable = false;
                    _userManager.RemoveFromRoleAsync(user, role.Name);
                }
            }
            if (shouldEnable)
            {
                _userManager.AddToRoleAsync(user, role.Name).Wait();
            }
            return;
        }

        public string GetRoleIdByName(string name)
        {
            var task = _roleManager.FindByNameAsync(name);
            task.Wait();
            var role = task.Result;

            return role.Id;
        }
    }

Creating Roles

You can create a new role with the CreateRole method. Just provide the name of the role, and it will be created.

Toggling Roles

You can add and remove roles that are assigned to a user with the ToggleUserRole method.

Provide the ID of the user and the ID of the role to initiate the roggle. You can always get the role ID via the GetRoleIdByName method.


Article Categories: # .net # c# # identity # asp.net
Date Published: Nov 23, 2020

About

A tech blog by Andy P. I talk about coding, enterprise software development, tech, games design & other things that interest me.

Signup To The Newsletter

I try to post a new interesting article every saturday.

IT Asset Management

Our friends at AssetPad are building a complete online solution for managing the IT assets within your organisation. With barcodes and documentation tools.