OpenLightGroup Blog

rss

Blogs from OpenLightGroup.net


Creating User and Roles Administration Pages for an MVC5 Application

image

You can easily build a User and Role management for you MVC 5 site that is using ASP.NET Identity.

This code is based on An HTML MVC LightSwitch Security Administration that is based on lsWires project by Dale Morrison.

image

Only users in the Administration role can see and use the Administration link.

image

The main screen is searchable and has paging.

You can click the Create New button to create a new user.

You can click the Edit Roles button to edit the master list of Roles for the application.

image

Clicking the Edit button next to a user navigates to the Edit User page.

You can click on the Edit Roles button to edit roles for the selected user.

image

You can add Roles to a user by selecting the Role in the dropdown and clicking the Add Role button.

You can remove a Role by clicking the Delete button on its row.

 

Creating the Application

 

image

Using Visual Studio 2015, select File then New then Project.

image

Create an ASP.NET Web Application.

image

Select the MVC template and insure that Individual User Accounts is selected for Authentication (if not use the Change Authentication button to change it).

Click the OK button.

image

The project will be created.

 

Install Nuget Package

 

image

A Nuget package to support paging on the Administration screen is required.

Select Tools then NuGet package Manager, then Package Manager Console.

image

Click to the right of the PM> symbol and paste:

Install-Package PagedList.Mvc

Press enter and the package will be installed.

 

Run The Application

 

image

Hit F5 to run the application.

Click the Register button to create a user.

image

Create a Test user.

image

The user will be created.

Close the web browser to stop the application.

image

In Visual Studio, click the Show All Files button, and expand the App_Data folder to see the database.

Right-click on it and select Include In Project.

image

From the toolbar, select View then Server Explorer.

image

In the Server Explorer, expand the DefaultConnection node and right-click on the AspNetUsers table and select Show Table Data.

image

You will see the Test user.

image

Right-click on the DefaultConnection node and select Close Connection so that we don’t potentially lock the database when running the application.

 

Enable Roles

 

image

Even though the Roles tables have been created, you cannot use them because Roles are not enabled when you initially create an MVC 5 project.

To understand how and where we enable Roles, note that the Startup.cs file (that runs when the application is started) calls a ConfigureAuth method.

image

This calls the ConfigureAuth method in the Startup.Auth.cs file.

In this file we add:

image

To support this code, we add the following to the IdentityConfig.cs file:

 

image

 

image

Build the solution.

The project should build without errors.

 

Add The Model Classes

 

image

The remaining code will require several model classes.

Add a file called UserRolesDTO.cs to the Models folder using the following code:

 

image
 

Create Administrator (if needed)

 

image

To create an Administrator of the application, add the following lines to the Web.config (note that the application has two files named Web.config), in the root of the application:

image

Add the following code to the Login method in the AccountController.cs file:

 

    // Create the Admin account using setting in Web.Config (if needed)
    CreateAdminIfNeeded();

 

Add the following code at the end of the class to implement the method and support the code:

 

        // Utility
        // Add RoleManager
        #region public ApplicationRoleManager RoleManager
        private ApplicationRoleManager _roleManager;
        public ApplicationRoleManager RoleManager
        {
            get
            {
                return _roleManager ?? HttpContext.GetOwinContext().GetUserManager();
            }
            private set
            {
                _roleManager = value;
            }
        }
        #endregion
        // Add CreateAdminIfNeeded
        #region private void CreateAdminIfNeeded()
        private void CreateAdminIfNeeded()
        {
            // Get Admin Account
            string AdminUserName = ConfigurationManager.AppSettings["AdminUserName"];
            string AdminPassword = ConfigurationManager.AppSettings["AdminPassword"];
            // See if Admin exists
            var objAdminUser = UserManager.FindByEmail(AdminUserName);
            if (objAdminUser == null)
            {
                //See if the Admin role exists
                if (!RoleManager.RoleExists("Administrator"))
                {
                    // Create the Admin Role (if needed)
                    IdentityRole objAdminRole = new IdentityRole("Administrator");
                    RoleManager.Create(objAdminRole);
                }
                // Create Admin user
                var objNewAdminUser = new ApplicationUser { UserName = AdminUserName, Email = AdminUserName };
                var AdminUserCreateResult = UserManager.Create(objNewAdminUser, AdminPassword);
                // Put user in Admin role
                UserManager.AddToRole(objNewAdminUser.Id, "Administrator");
            }
        }
        #endregion

 

Add the following using statements to the class:

 

  using Microsoft.AspNet.Identity.EntityFramework;
  using System.Configuration;

 

When a user attempts to log in, the code will run and create the Administrator account, if it does not already exist, and place that account in the Administrator group.

 

Create the Administration Page

 

image

Create a View page at View/Admin/Index.cshtml using the following code:

image

image

To support the code in the View, create a Controller class at Controllers/AdminController.cs using the following code:

 

#region Includes
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity.EntityFramework;
using EndToEnd.Models;
using PagedList;
#endregion Includes
namespace EndToEnd.Controllers
{
    public class AdminController : Controller
    {
        private ApplicationUserManager _userManager;
        private ApplicationRoleManager _roleManager;
        // Controllers
        // GET: /Admin/
        [Authorize(Roles = "Administrator")]
        #region public ActionResult Index(string searchStringUserNameOrEmail)
        public ActionResult Index(string searchStringUserNameOrEmail, string currentFilter, int? page)
        {
            try
            {
                int intPage = 1;
                int intPageSize = 5;
                int intTotalPageCount = 0;
                if (searchStringUserNameOrEmail != null)
                {
                    intPage = 1;
                }
                else
                {
                    if (currentFilter != null)
                    {
                        searchStringUserNameOrEmail = currentFilter;
                        intPage = page ?? 1;
                    }
                    else
                    {
                        searchStringUserNameOrEmail = "";
                        intPage = page ?? 1;
                    }
                }
                ViewBag.CurrentFilter = searchStringUserNameOrEmail;
                List col_UserDTO = new List();
                int intSkip = (intPage - 1) * intPageSize;
                intTotalPageCount = UserManager.Users
                    .Where(x => x.UserName.Contains(searchStringUserNameOrEmail))
                    .Count();
                var result = UserManager.Users
                    .Where(x => x.UserName.Contains(searchStringUserNameOrEmail))
                    .OrderBy(x => x.UserName)
                    .Skip(intSkip)
                    .Take(intPageSize)
                    .ToList();
                foreach (var item in result)
                {
                    ExpandedUserDTO objUserDTO = new ExpandedUserDTO();
                    objUserDTO.UserName = item.UserName;
                    objUserDTO.Email = item.Email;
                    objUserDTO.LockoutEndDateUtc = item.LockoutEndDateUtc;
                    col_UserDTO.Add(objUserDTO);
                }
                // Set the number of pages
                var _UserDTOAsIPagedList =
                    new StaticPagedList
                    (
                        col_UserDTO, intPage, intPageSize, intTotalPageCount
                        );
                return View(_UserDTOAsIPagedList);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, "Error: " + ex);
                List col_UserDTO = new List();
                return View(col_UserDTO.ToPagedList(1, 25));
            }
        }
        #endregion
        
        // Utility
        #region public ApplicationUserManager UserManager
        public ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ??
                    HttpContext.GetOwinContext()
                    .GetUserManager();
            }
            private set
            {
                _userManager = value;
            }
        }
        #endregion
        #region public ApplicationRoleManager RoleManager
        public ApplicationRoleManager RoleManager
        {
            get
            {
                return _roleManager ??
                    HttpContext.GetOwinContext()
                    .GetUserManager();
            }
            private set
            {
                _roleManager = value;
            }
        }
        #endregion
    }
}

 

image

To create a button that will navigate to the View, add the following code to the file at View/Shared/_Layout.cshtml:

 

    @if (User.IsInRole("Administrator"))
    {
        <li>@Html.ActionLink("Administration", "Index", "Admin")li>
    }

 

This code will only show the Administration link to users in the Administration role.

 

Run The Application

 

image

Run the application and click the Log In button.

image

Log in as the Administrator using the username and password that was added to the Web.config file earlier.

image

You will then see the Administration link. Clicking the link will navigate to the Administration page (however the buttons will not work yet).

Close the web browser to stop the application.

 

Create and Edit Roles

 

image

To allow the Administrator to edit the Roles of the application, create a View page at View/Admin/ViewAllRoles.cshtml using the following code:

 

@model IEnumerable<EndToEnd.Models.RoleDTO>
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<br />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<p>
    @Html.ActionLink("Back to List", "Index", null, new { @class = "btn btn-default" })
    @Html.ActionLink("Add Role", "AddRole", null, new { @class = "btn btn-default" })
p>
<table class="table">
    <tr>
        <th>
            Role
        th>
        <th>th>
    tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.RoleName)
            td>
            <td>
                @if (item.RoleName.ToLower() != "administrator")
                {
                    @Html.ActionLink("Delete", "DeleteUserRole",
                   new { RoleName = item.RoleName },
                   new
                   {
                       onclick =
                   "return confirm('Are you sure you wish to delete this role?');"
                   })
                }
            td>
        tr>
    }
table>

 

image

Also, create a View page at View/Admin/AddRole.cshtml using the following code:

image

image

Add the following code to the AdminController.cs file:

 

        // Roles *****************************
        // GET: /Admin/ViewAllRoles
        [Authorize(Roles = "Administrator")]
        #region public ActionResult ViewAllRoles()
        public ActionResult ViewAllRoles()
        {
            var roleManager =
                new RoleManager
                (
                    new RoleStore(new ApplicationDbContext())
                    );
            List colRoleDTO = (from objRole in roleManager.Roles
                                        select new RoleDTO
                                        {
                                            Id = objRole.Id,
                                            RoleName = objRole.Name
                                        }).ToList();
            return View(colRoleDTO);
        }
        #endregion
        // GET: /Admin/AddRole
        [Authorize(Roles = "Administrator")]
        #region public ActionResult AddRole()
        public ActionResult AddRole()
        {
            RoleDTO objRoleDTO = new RoleDTO();
            return View(objRoleDTO);
        }
        #endregion
        // PUT: /Admin/AddRole
        [Authorize(Roles = "Administrator")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        #region public ActionResult AddRole(RoleDTO paramRoleDTO)
        public ActionResult AddRole(RoleDTO paramRoleDTO)
        {
            try
            {
                if (paramRoleDTO == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                var RoleName = paramRoleDTO.RoleName.Trim();
                if (RoleName == "")
                {
                    throw new Exception("No RoleName");
                }
                // Create Role
                var roleManager =
                    new RoleManager(
                        new RoleStore(new ApplicationDbContext())
                        );
                if (!roleManager.RoleExists(RoleName))
                {
                    roleManager.Create(new IdentityRole(RoleName));
                }
                return Redirect("~/Admin/ViewAllRoles");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, "Error: " + ex);
                return View("AddRole");
            }
        }
        #endregion
        // DELETE: /Admin/DeleteUserRole?RoleName=TestRole
        [Authorize(Roles = "Administrator")]
        #region public ActionResult DeleteUserRole(string RoleName)
        public ActionResult DeleteUserRole(string RoleName)
        {
            try
            {
                if (RoleName == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                if (RoleName.ToLower() == "administrator")
                {
                    throw new Exception(String.Format("Cannot delete {0} Role.", RoleName));
                }
                var roleManager =
                    new RoleManager(
                        new RoleStore(new ApplicationDbContext()));
                var UsersInRole = roleManager.FindByName(RoleName).Users.Count();
                if (UsersInRole > 0)
                {
                    throw new Exception(
                        String.Format(
                            "Canot delete {0} Role because it still has users.",
                            RoleName)
                            );
                }
                var objRoleToDelete = (from objRole in roleManager.Roles
                                       where objRole.Name == RoleName
                                       select objRole).FirstOrDefault();
                if (objRoleToDelete != null)
                {
                    roleManager.Delete(objRoleToDelete);
                }
                else
                {
                    throw new Exception(
                        String.Format(
                            "Cannot delete {0} Role does not exist.",
                            RoleName)
                            );
                }
                List colRoleDTO = (from objRole in roleManager.Roles
                                            select new RoleDTO
                                            {
                                                Id = objRole.Id,
                                                RoleName = objRole.Name
                                            }).ToList();
                return View("ViewAllRoles", colRoleDTO);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, "Error: " + ex);
                var roleManager =
                    new RoleManager(
                        new RoleStore(new ApplicationDbContext()));
                List colRoleDTO = (from objRole in roleManager.Roles
                                            select new RoleDTO
                                            {
                                                Id = objRole.Id,
                                                RoleName = objRole.Name
                                            }).ToList();
                return View("ViewAllRoles", colRoleDTO);
            }
        }
        #endregion

 

image

Run the application, log in as the Administrator, navigate to the Administration screen, and click the Edit Roles button.

image

You can click the Add Role button to create Roles and the Delete button to delete them.

You cannot delete the Administrator role because the code in the ViewAllRoles.cshtml page prevents this.

 

Create Users

 

image

To allow the Administrator to create users, create a View page at View/Admin/Create.cshtml using the following code:

image

 

image

 

Add the following code to the AdminController.cs file:

 

        // Users *****************************
        // GET: /Admin/Edit/Create 
        [Authorize(Roles = "Administrator")]
        #region public ActionResult Create()
        public ActionResult Create()
        {
            ExpandedUserDTO objExpandedUserDTO = new ExpandedUserDTO();
            ViewBag.Roles = GetAllRolesAsSelectList();
            return View(objExpandedUserDTO);
        }
        #endregion
        // PUT: /Admin/Create
        [Authorize(Roles = "Administrator")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        #region public ActionResult Create(ExpandedUserDTO paramExpandedUserDTO)
        public ActionResult Create(ExpandedUserDTO paramExpandedUserDTO)
        {
            try
            {
                if (paramExpandedUserDTO == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                var Email = paramExpandedUserDTO.Email.Trim();
                var UserName = paramExpandedUserDTO.Email.Trim();
                var Password = paramExpandedUserDTO.Password.Trim();
                if (Email == "")
                {
                    throw new Exception("No Email");
                }
                if (Password == "")
                {
                    throw new Exception("No Password");
                }
                // UserName is LowerCase of the Email
                UserName = Email.ToLower();
                // Create user
                var objNewAdminUser = new ApplicationUser { UserName = UserName, Email = Email };
                var AdminUserCreateResult = UserManager.Create(objNewAdminUser, Password);
                if (AdminUserCreateResult.Succeeded == true)
                {
                    string strNewRole = Convert.ToString(Request.Form["Roles"]);
                    if (strNewRole != "0")
                    {
                        // Put user in role
                        UserManager.AddToRole(objNewAdminUser.Id, strNewRole);
                    }
                    return Redirect("~/Admin");
                }
                else
                {
                    ViewBag.Roles = GetAllRolesAsSelectList();
                    ModelState.AddModelError(string.Empty,
                        "Error: Failed to create the user. Check password requirements.");
                    return View(paramExpandedUserDTO);
                }
            }
            catch (Exception ex)
            {
                ViewBag.Roles = GetAllRolesAsSelectList();
                ModelState.AddModelError(string.Empty, "Error: " + ex);
                return View("Create");
            }
        }
        #endregion

 

Add the following in the Utility region in the class to support the code:

 

        #region private List GetAllRolesAsSelectList()
        private List GetAllRolesAsSelectList()
        {
            List SelectRoleListItems =
                new List();
            var roleManager =
                new RoleManager(
                    new RoleStore(new ApplicationDbContext()));
            var colRoleSelectList = roleManager.Roles.OrderBy(x => x.Name).ToList();
            SelectRoleListItems.Add(
                new SelectListItem
                {
                    Text = "Select",
                    Value = "0"
                });
            foreach (var item in colRoleSelectList)
            {
                SelectRoleListItems.Add(
                    new SelectListItem
                    {
                        Text = item.Name.ToString(),
                        Value = item.Name.ToString()
                    });
            }
            return SelectRoleListItems;
        }
        #endregion

 

This creates a dropdown of all possible roles to choose from when creating a user.

 

image

Run the application, log in as the Administrator, navigate to the Administration screen, and click the Create User button.

You will be able to create users and select their initial Role.

 

Edit Users

 

image

To allow a user to be edited, create a View page at View/Admin/EditUser.cshtml using the following code:

 

image

image

image

 

Add the following code to the AdminController.cs file:

 

        // GET: /Admin/Edit/TestUser 
        [Authorize(Roles = "Administrator")]
        #region public ActionResult EditUser(string UserName)
        public ActionResult EditUser(string UserName)
        {
            if (UserName == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            ExpandedUserDTO objExpandedUserDTO = GetUser(UserName);
            if (objExpandedUserDTO == null)
            {
                return HttpNotFound();
            }
            return View(objExpandedUserDTO);
        }
        #endregion
        // PUT: /Admin/EditUser
        [Authorize(Roles = "Administrator")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        #region public ActionResult EditUser(ExpandedUserDTO paramExpandedUserDTO)
        public ActionResult EditUser(ExpandedUserDTO paramExpandedUserDTO)
        {
            try
            {
                if (paramExpandedUserDTO == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                ExpandedUserDTO objExpandedUserDTO = UpdateDTOUser(paramExpandedUserDTO);
                if (objExpandedUserDTO == null)
                {
                    return HttpNotFound();
                }
                return Redirect("~/Admin");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, "Error: " + ex);
                return View("EditUser", GetUser(paramExpandedUserDTO.UserName));
            }
        }
        #endregion
        // DELETE: /Admin/DeleteUser
        [Authorize(Roles = "Administrator")]
        #region public ActionResult DeleteUser(string UserName)
        public ActionResult DeleteUser(string UserName)
        {
            try
            {
                if (UserName == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                if (UserName.ToLower() == this.User.Identity.Name.ToLower())
                {
                    ModelState.AddModelError(
                        string.Empty, "Error: Cannot delete the current user");
                    return View("EditUser");
                }
                ExpandedUserDTO objExpandedUserDTO = GetUser(UserName);
                if (objExpandedUserDTO == null)
                {
                    return HttpNotFound();
                }
                else
                {
                    DeleteUser(objExpandedUserDTO);
                }
                return Redirect("~/Admin");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, "Error: " + ex);
                return View("EditUser", GetUser(UserName));
            }
        }
        #endregion

 

Add the following in the Utility region in the class to support the code:

 

    #region private ExpandedUserDTO UpdateDTOUser(ExpandedUserDTO objExpandedUserDTO)
        private ExpandedUserDTO UpdateDTOUser(ExpandedUserDTO paramExpandedUserDTO)
        {
            ApplicationUser result =
                UserManager.FindByName(paramExpandedUserDTO.UserName);
            // If we could not find the user, throw an exception
            if (result == null)
            {
                throw new Exception("Could not find the User");
            }
            result.Email = paramExpandedUserDTO.Email;
            // Lets check if the account needs to be unlocked
            if (UserManager.IsLockedOut(result.Id))
            {
                // Unlock user
                UserManager.ResetAccessFailedCountAsync(result.Id);
            }
            UserManager.Update(result);
            // Was a password sent across?
            if (!string.IsNullOrEmpty(paramExpandedUserDTO.Password))
            {
                // Remove current password
                var removePassword = UserManager.RemovePassword(result.Id);
                if (removePassword.Succeeded)
                {
                    // Add new password
                    var AddPassword =
                        UserManager.AddPassword(
                            result.Id,
                            paramExpandedUserDTO.Password
                            );
                    if (AddPassword.Errors.Count() > 0)
                    {
                        throw new Exception(AddPassword.Errors.FirstOrDefault());
                    }
                }
            }
            return paramExpandedUserDTO;
        }
        #endregion
        #region private void DeleteUser(ExpandedUserDTO paramExpandedUserDTO)
        private void DeleteUser(ExpandedUserDTO paramExpandedUserDTO)
        {
            ApplicationUser user = 
                UserManager.FindByName(paramExpandedUserDTO.UserName);
            // If we could not find the user, throw an exception
            if (user == null)
            {
                throw new Exception("Could not find the User");
            }
            UserManager.RemoveFromRoles(user.Id, UserManager.GetRoles(user.Id).ToArray());
            UserManager.Update(user);
            UserManager.Delete(user);
        }
        #endregion

 

image

Run the application, log in as the Administrator and navigate to the Administration screen.

You will be able to Edit and Delete users.

 

Edit Roles For User

 

image

To allow the Roles for a user to be edited, create a View page at View/Admin/EditRoles.cshtml using the following code:

 

@model EndToEnd.Models.UserAndRolesDTO
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <br />
    @Html.ValidationSummary(true,
    "",
    new { @class = "text-danger" })
    <div>
        @Html.ActionLink("Back",
       "EditUser",
       new { UserName = Model.UserName },
       new { @class = "btn btn-default" })
        <input type="submit" value="Add Role" class="btn btn-default" />
        @Html.DropDownList("AddRole")
    div>
    <br />
    <table class="table">
        <tr>
            <th>
                Existing Roles:
            th>
            <th>th>
        tr>
        @foreach (var item in Model.colUserRoleDTO)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.RoleName)
                td>
                <td>
                    @if (!((Model.UserName.ToLower() ==
                        this.User.Identity.Name.ToLower()) &&
                        item.RoleName == "Administrator") &&
                        item.RoleName != "No Roles Found")
                    {
                        @Html.ActionLink("Delete", "DeleteRole",
                       new { UserName = item.UserName, RoleName = item.RoleName },
                        new
                        {
                            onclick =
                        "return confirm('Are you sure you wish to delete this role?');"
                        })
                    }
                td>
            tr>
        }
    table>
}

 

image

 

Add the following code to the AdminController.cs file:

 

        // GET: /Admin/EditRoles/TestUser 
        [Authorize(Roles = "Administrator")]
        #region ActionResult EditRoles(string UserName)
        public ActionResult EditRoles(string UserName)
        {
            if (UserName == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            UserName = UserName.ToLower();
            // Check that we have an actual user
            ExpandedUserDTO objExpandedUserDTO = GetUser(UserName);
            if (objExpandedUserDTO == null)
            {
                return HttpNotFound();
            }
            UserAndRolesDTO objUserAndRolesDTO =
                GetUserAndRoles(UserName);
            return View(objUserAndRolesDTO);
        }
        #endregion
        // PUT: /Admin/EditRoles/TestUser 
        [Authorize(Roles = "Administrator")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        #region public ActionResult EditRoles(UserAndRolesDTO paramUserAndRolesDTO)
        public ActionResult EditRoles(UserAndRolesDTO paramUserAndRolesDTO)
        {
            try
            {
                if (paramUserAndRolesDTO == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                string UserName = paramUserAndRolesDTO.UserName;
                string strNewRole = Convert.ToString(Request.Form["AddRole"]);
                if (strNewRole != "No Roles Found")
                {
                    // Go get the User
                    ApplicationUser user = UserManager.FindByName(UserName);
                    // Put user in role
                    UserManager.AddToRole(user.Id, strNewRole);
                }
                ViewBag.AddRole = new SelectList(RolesUserIsNotIn(UserName));
                UserAndRolesDTO objUserAndRolesDTO =
                    GetUserAndRoles(UserName);
                return View(objUserAndRolesDTO);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, "Error: " + ex);
                return View("EditRoles");
            }
        }
        #endregion
        // DELETE: /Admin/DeleteRole?UserName="TestUser&RoleName=Administrator
        [Authorize(Roles = "Administrator")]
        #region public ActionResult DeleteRole(string UserName, string RoleName)
        public ActionResult DeleteRole(string UserName, string RoleName)
        {
            try
            {
                if ((UserName == null) || (RoleName == null))
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                UserName = UserName.ToLower();
                // Check that we have an actual user
                ExpandedUserDTO objExpandedUserDTO = GetUser(UserName);
                if (objExpandedUserDTO == null)
                {
                    return HttpNotFound();
                }
                if (UserName.ToLower() ==
                    this.User.Identity.Name.ToLower() && RoleName == "Administrator")
                {
                    ModelState.AddModelError(string.Empty,
                        "Error: Cannot delete Administrator Role for the current user");
                }
                // Go get the User
                ApplicationUser user = UserManager.FindByName(UserName);
                // Remove User from role
                UserManager.RemoveFromRoles(user.Id, RoleName);
                UserManager.Update(user);
                ViewBag.AddRole = new SelectList(RolesUserIsNotIn(UserName));
                return RedirectToAction("EditRoles", new { UserName = UserName });
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, "Error: " + ex);
                ViewBag.AddRole = new SelectList(RolesUserIsNotIn(UserName));
                UserAndRolesDTO objUserAndRolesDTO =
                    GetUserAndRoles(UserName);
                return View("EditRoles", objUserAndRolesDTO);
            }
        }
        #endregion

 

 

Add the following in the Utility region in the class to support the code:

 

        #region private UserAndRolesDTO GetUserAndRoles(string UserName)
        private UserAndRolesDTO GetUserAndRoles(string UserName)
        {
            // Go get the User
            ApplicationUser user = UserManager.FindByName(UserName);
            List colUserRoleDTO =
                (from objRole in UserManager.GetRoles(user.Id)
                 select new UserRoleDTO
                 {
                     RoleName = objRole,
                     UserName = UserName
                 }).ToList();
            if (colUserRoleDTO.Count() == 0)
            {
                colUserRoleDTO.Add(new UserRoleDTO { RoleName = "No Roles Found" });
            }
            ViewBag.AddRole = new SelectList(RolesUserIsNotIn(UserName));
            // Create UserRolesAndPermissionsDTO
            UserAndRolesDTO objUserAndRolesDTO =
                new UserAndRolesDTO();
            objUserAndRolesDTO.UserName = UserName;
            objUserAndRolesDTO.colUserRoleDTO = colUserRoleDTO;
            return objUserAndRolesDTO;
        }
        #endregion
        #region private List<string> RolesUserIsNotIn(string UserName)
        private List<string> RolesUserIsNotIn(string UserName)
        {
            // Get roles the user is not in
            var colAllRoles = RoleManager.Roles.Select(x => x.Name).ToList();
            // Go get the roles for an individual
            ApplicationUser user = UserManager.FindByName(UserName);
            // If we could not find the user, throw an exception
            if (user == null)
            {
                throw new Exception("Could not find the User");
            }
            var colRolesForUser = UserManager.GetRoles(user.Id).ToList();
            var colRolesUserInNotIn = (from objRole in colAllRoles
                                       where !colRolesForUser.Contains(objRole)
                                       select objRole).ToList();
            if (colRolesUserInNotIn.Count() == 0)
            {
                colRolesUserInNotIn.Add("No Roles Found");
            }
            return colRolesUserInNotIn;
        }
        #endregion

 

 

image

Run the application, log in as the Administrator and navigate to the Administration screen.

You will be able to select Edit for a user...

image

… then select Edit Roles for a user…

image

… then add and delete Roles for the selected user.

 

Special Thanks

 

This code is based on lsWires project by Dale Morrison.

 

Download

 

You can download the code at the following link:

EndToEnd_MVC5_Administration.zip





Comments are closed.
Showing 3 Comments
Avatar  Rick Hubka last year

Very Nice! One the the few tutorials that actually works

Avatar  [Pingback] last year

Pingback from alvinashcraft.com

https://www.alvinashcraft.com/2016/03/08/dew-drop-march-8-2016-2203/

Avatar  [Pingback] last year

Pingback from compksoft.eu

OpenLightGroup Blog | Creating User and Roles Administration Pages for an MVC5 Application | CompkSofthttp://compksoft.eu/?p=34568