Authentication and authorization using ASP.NET MVC

5 minute read

Step1: Select ASP.NET Web Application (.NET Framework)

Step2: Type project and solution name
Type project name as “MVCAuth” and also solution name as “MVC Auth”

Step 3: Select project template

  • Select project template as Web Application (Model-View-Controller)
  • Change authentication to Individual User Authentication
  • Click create button

Step 4: Change web.config file

<add name="DefaultConnection" connectionString="Data Source=localhost;Initial Catalog=AuthDB;Persist Security Info=False;User ID=sa; Password=mahedee.net; Pooling=False;MultipleActiveResultSets=False;Encrypt=False;TrustServerCertificate=False" providerName="System.Data.SqlClient" />

Step 5: Add some model and view model class

  • Create Role Model class in Models folder as follows
     public class Role : IdentityRole
      {
    
      }
    
  • Create UserRoleVM View Model class in Models folder as follows
      public class UserRoleVM
      {
          public string UserId { get; set; }
          public string RoleId { get; set; }
    
          public string UserName { get; set; }
          public string RoleName { get; set; }
      }
    
  • Create UsersRolesVM View Model class in Models folder as follows
      public class UsersRolesVM
      {
          //public string UserName { get; set; }
          public ApplicationUser User { get; set; }
    
          public IEnumerable<string> RoleNames { get; set; }
      }
    

Step 6: Add Controllers to the application

  • Add RolesController in Controllers folder
  • Choose template MVC 5 Controller with read/write actions
  • Modify RolesController as follows
    public class RolesController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();
        // GET: Roles
        public ActionResult Index()
        {
            var roleStore = new RoleStore<IdentityRole>(db);
            var roleManager = new RoleManager<IdentityRole>(roleStore);
            var roles = roleManager.Roles.ToList();
            return View(roles);
        }

        // GET: Roles/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        // GET: Roles/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Roles/Create
        [HttpPost]
        public ActionResult Create(IdentityRole role)
        {
            try
            {
                // TODO: Add insert logic here

                var roleStore = new RoleStore<IdentityRole>(db);
                var roleManager = new RoleManager<IdentityRole>(roleStore);

                if(!roleManager.RoleExists(role.Name))
                {
                    roleManager.Create(role);
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Roles/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        // POST: Roles/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Roles/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        // POST: Roles/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
  • Add UsersRoleController in Controllers folder
  • Choose template MVC 5 Controller with read/write actions
  • Modify UsersRoleController as follows
    public class UsersRoleController : Controller
    {
        ApplicationDbContext db = new ApplicationDbContext();
        // GET: UsersRole
        public ActionResult Index()
        {
            List<UsersRolesVM> usersRolesVMs = new List<UsersRolesVM>();
            List<ApplicationUser> users = db.Users.ToList();

            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));

            foreach (ApplicationUser user in users)
            {
                UsersRolesVM usersRolesVM = new UsersRolesVM();
                usersRolesVM.User = user;
                usersRolesVM.RoleNames = userManager.GetRoles(user.Id);
                usersRolesVMs.Add(usersRolesVM);
            }
            return View(usersRolesVMs);
        }

        // GET: UsersRole/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        // GET: UsersRole/Create
        public ActionResult Create()
        {

            var roleStore = new RoleStore<IdentityRole>(db);
            var roleManager = new RoleManager<IdentityRole>(roleStore);
            var roles = roleManager.Roles.ToList();


            ViewBag.UserId = new SelectList(db.Users.ToList(), "Id", "UserName");
            ViewBag.RoleName = new SelectList(roles, "Name", "Name");

            return View();
        }

        // POST: UsersRole/Create
        [HttpPost]
        //public ActionResult Create(FormCollection collection)
        public ActionResult Create(UserRoleVM userRole)
        {
            try
            {
               if(userRole != null)
                {
                    var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
                    userManager.AddToRole(userRole.UserId, userRole.RoleName);
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: UsersRole/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        // POST: UsersRole/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: UsersRole/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        // POST: UsersRole/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }

Step 7: Create Roles View to the application

  • Add Index View in Views->Roles folder
  • Add Create View in Views->Roles folder
  • Modify views as follows

Index.cshtml

@model IEnumerable<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr>
}

</table>

Create.cshtml

@*@model MVCAuth.Models.Role*@
@model Microsoft.AspNet.Identity.EntityFramework.IdentityRole

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Role</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


Step 8: Create UsersRole View to the application

  • Add Index View in Views->UsersRole folder
  • Add Create View in Views->UsersRole folder
  • Modify views as follows

Index.cshtml

@model IEnumerable<MVCAuth.Models.UsersRolesVM>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @*@Html.DisplayNameFor(model => model.UserName)*@
            User Name
        </th>
        <th>
            @*@Html.DisplayNameFor(model => model.RoleName)*@
            Roles Name
        </th>
        <th></th>
    </tr>

    @foreach (var users in Model)
    {

        foreach (string rolesName in users.RoleNames)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => users.User.UserName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => rolesName)
                </td>
                <td>
                    @Html.ActionLink("Delete", "Delete", new { id = 1 })
                </td>
            </tr>
        }
    }

</table>

Create.cshtml

@model MVCAuth.Models.UserRoleVM

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
<div class="form-horizontal">
    <h4>UserRoleVM</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    <div class="form-group">
        @Html.LabelFor(model => model.UserName, "UserName", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("UserId", null, htmlAttributes: new { @class = "form-control" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.RoleName, "RoleName", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("RoleName", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Step 9: Run migration command in package manager console

Now the application is ready to run.

Source Code