Introduction

This article will explain the role-based authentication in ASP.NET MVC, with examples. I strongly recommended reading my previous articles before proceeding to this article as it is a continuation part of my previous article.
Step 1
Open your favourite SQL Server database with any version. It really doesn’t matter what version it is. Create the following database data tables.
  1. create table Employee
  2. (
  3. EmpId int primary key identity (1,1),
  4. Name nvarchar(50),
  5. Gender char(10),
  6. Age int,
  7. Position nvarchar(50),
  8. Office nvarchar(50),
  9. HireDate datetime,
  10. Salary int,
  11. DepartmentId int
  12. )
  13. create table Department
  14. (
  15. DeptId int primary key identity(1,1),
  16. DepartmentName nvarchar(50)
  17. )
  18. create table Users
  19. (
  20. Id int primary key identity(1,1),
  21. Username nvarchar(50),
  22. Password nvarchar(50)
  23. )
  24. create table Roles
  25. (
  26. Id int primary key identity(1,1),
  27. RoleName nvarchar(50)
  28. )
  29. create table UserRoleMapping
  30. (
  31. Id int primary key identity(1,1),
  32. UserId int,
  33. RoleId int
  34. )
  35. alter table Employee Add foreign key
  36. (DepartmentId) references Department(DeptId)
  37. alter table UserRoleMapping Add foreign key(UserId)
  38. references Users(Id)
  39. alter table UserRoleMapping Add foreign key(RoleId)
  40. references Roles(id)
Step 2
Open Visual Studio 2015 or an editor of your choice and create a new project.
Step 3
Choose "web application" project and give an appropriate name to your project.
Role Based Authentication In ASP.NET MVC
Step 4
Select "empty" template, check on the MVC box, and click OK.
Role Based Authentication In ASP.NET MVC
Step 5
Right-click on the Models folder and add a database model. Add Entity Framework now. For that, right-click on Models folder, select Add, then select New Item.
Role Based Authentication In ASP.NET MVC
You will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name EmployeeModel (this name is not mandatory, you can give any name) and click "Add".
Role Based Authentication In ASP.NET MVC
After you click on "Add a window", the wizard will open. Choose EF Designer from the database and click "Next".
Role Based Authentication In ASP.NET MVC
After clicking on "Next", a window will appear. Choose New Connection. Another window will appear. Add your server name - if it is local, then enter a dot (.). Choose your database and click "OK".
Role Based Authentication In ASP.NET MVC
The connection will be added. If you wish, save the connection name as you want. You can change the name of your connection below. It will save the connection in the web config. Now, click "Next".
Role Based Authentication In ASP.NET MVC
After clicking on NEXT, another window will appear. Choose the database table name as shown in the below screenshot and click "Finish".
Role Based Authentication In ASP.NET MVC
Entity Framework gets added and the respective class gets generated under the Models folder.
Role Based Authentication In ASP.NET MVC
Step 6
Right-click on Controllers folder and add a controller.
Role Based Authentication In ASP.NET MVC
A window will appear. Choose MVC5 Controller with views, using Entity Framework and click "Add".
Role Based Authentication In ASP.NET MVC
After clicking on "Add", another window will appear. Choose Model Class and data context class and click "Add". The EmployeesController will be added under the Controllers folder with respective views.
Role Based Authentication In ASP.NET MVC
Modify Employees Controller Code
  1. using MvcRoleBasedAuthentication_Demo.Models;
  2. using System.Data.Entity;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Web.Mvc;
  6. namespace MvcRoleBasedAuthentication_Demo.Controllers
  7. {
  8. public class EmployeesController : Controller
  9. {
  10. private EmployeeContext db = new EmployeeContext();
  11. [Authorize(Roles ="Admin,Employee")]
  12. public ActionResult Index()
  13. {
  14. var employees = db.Employees.Include(e => e.Department);
  15. return View(employees.ToList());
  16. }
  17. [Authorize(Roles = "Admin,Employee")]
  18. public ActionResult Details(int? id)
  19. {
  20. if (id == null)
  21. {
  22. return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
  23. }
  24. Employee employee = db.Employees.Find(id);
  25. if (employee == null)
  26. {
  27. return HttpNotFound();
  28. }
  29. return View(employee);
  30. }
  31. [Authorize(Roles = "Employee")]
  32. public ActionResult Create()
  33. {
  34. ViewBag.DepartmentId = new SelectList(db.Departments, "DeptId", "DepartmentName");
  35. return View();
  36. }
  37. [Authorize(Roles = "Employee")]
  38. [HttpPost]
  39. [ValidateAntiForgeryToken]
  40. public ActionResult Create([Bind(Include = "EmpId,Name,Gender,Age,Position,Office,HireDate,Salary,DepartmentId")] Employee employee)
  41. {
  42. if (ModelState.IsValid)
  43. {
  44. db.Employees.Add(employee);
  45. db.SaveChanges();
  46. return RedirectToAction("Index");
  47. }
  48. ViewBag.DepartmentId = new SelectList(db.Departments, "DeptId", "DepartmentName", employee.DepartmentId);
  49. return View(employee);
  50. }
  51. [Authorize(Roles = "Employee")]
  52. public ActionResult Edit(int? id)
  53. {
  54. if (id == null)
  55. {
  56. return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
  57. }
  58. Employee employee = db.Employees.Find(id);
  59. if (employee == null)
  60. {
  61. return HttpNotFound();
  62. }
  63. ViewBag.DepartmentId = new SelectList(db.Departments, "DeptId", "DepartmentName", employee.DepartmentId);
  64. return View(employee);
  65. }
  66. [Authorize(Roles = "Employee")]
  67. [HttpPost]
  68. [ValidateAntiForgeryToken]
  69. public ActionResult Edit([Bind(Include = "EmpId,Name,Gender,Age,Position,Office,HireDate,Salary,DepartmentId")] Employee employee)
  70. {
  71. if (ModelState.IsValid)
  72. {
  73. db.Entry(employee).State = EntityState.Modified;
  74. db.SaveChanges();
  75. return RedirectToAction("Index");
  76. }
  77. ViewBag.DepartmentId = new SelectList(db.Departments, "DeptId", "DepartmentName", employee.DepartmentId);
  78. return View(employee);
  79. }
  80. [Authorize(Roles = "Admin,Employee")]
  81. public ActionResult Delete(int? id)
  82. {
  83. if (id == null)
  84. {
  85. return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
  86. }
  87. Employee employee = db.Employees.Find(id);
  88. if (employee == null)
  89. {
  90. return HttpNotFound();
  91. }
  92. return View(employee);
  93. }
  94. [Authorize(Roles = "Admin,Employee")]
  95. [HttpPost, ActionName("Delete")]
  96. [ValidateAntiForgeryToken]
  97. public ActionResult DeleteConfirmed(int id)
  98. {
  99. Employee employee = db.Employees.Find(id);
  100. db.Employees.Remove(employee);
  101. db.SaveChanges();
  102. return RedirectToAction("Index");
  103. }
  104. protected override void Dispose(bool disposing)
  105. {
  106. if (disposing)
  107. {
  108. db.Dispose();
  109. }
  110. base.Dispose(disposing);
  111. }
  112. }
  113. }
Step 6
Right click on Models folder and create a UserRoleProvider class,
Role Based Authentication In ASP.NET MVC
Role Based Authentication In ASP.NET MVC
UserRoleProvider Class
  1. using System;
  2. using System.Linq;
  3. using System.Web.Security;
  4. namespace MvcRoleBasedAuthentication_Demo.Models
  5. {
  6. public class UserRoleProvider : RoleProvider
  7. {
  8. public override string ApplicationName
  9. {
  10. get
  11. {
  12. throw new NotImplementedException();
  13. }
  14. set
  15. {
  16. throw new NotImplementedException();
  17. }
  18. }
  19. public override void AddUsersToRoles(string[] usernames, string[] roleNames)
  20. {
  21. throw new NotImplementedException();
  22. }
  23. public override void CreateRole(string roleName)
  24. {
  25. throw new NotImplementedException();
  26. }
  27. public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
  28. {
  29. throw new NotImplementedException();
  30. }
  31. public override string[] FindUsersInRole(string roleName, string usernameToMatch)
  32. {
  33. throw new NotImplementedException();
  34. }
  35. public override string[] GetAllRoles()
  36. {
  37. throw new NotImplementedException();
  38. }
  39. public override string[] GetRolesForUser(string username)
  40. {
  41. using (EmployeeContext _Context=new EmployeeContext())
  42. {
  43. var userRoles = (from user in _Context.Users
  44. join roleMapping in _Context.UserRoleMappings
  45. on user.Id equals roleMapping.UserId
  46. join role in _Context.Roles
  47. on roleMapping.RoleId equals role.Id
  48. where user.Username == username
  49. select role.RoleName).ToArray();
  50. return userRoles;
  51. }
  52. }
  53. public override string[] GetUsersInRole(string roleName)
  54. {
  55. throw new NotImplementedException();
  56. }
  57. public override bool IsUserInRole(string username, string roleName)
  58. {
  59. throw new NotImplementedException();
  60. }
  61. public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
  62. {
  63. throw new NotImplementedException();
  64. }
  65. public override bool RoleExists(string roleName)
  66. {
  67. throw new NotImplementedException();
  68. }
  69. }
  70. }
Step 7
Open web config file and write the following code.
  1. <authentication mode="Forms">
  2. <forms loginUrl="Account/Login"></forms>
  3. </authentication>
  4. <roleManager defaultProvider="userRoleProvider" enabled="true">
  5. <providers>
  6. <clear/>
  7. <add name="userRoleProvider" type="MvcRoleBasedAuthentication_Demo.Models.UserRoleProvider"/>
  8. </providers>
  9. </roleManager>
Step 8
Open _Layout.cshtml file which under views folder in shared folder.
  1. <nav class="navbar navbar-expand-md bg-dark navbar-dark">
  2. <a class="navbar-brand" href="#">
  3. @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
  4. </a>
  5. <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
  6. <span class="navbar-toggler-icon"></span>
  7. </button>
  8. <div class="collapse navbar-collapse" id="collapsibleNavbar">
  9. <ul class="navbar-nav">
  10. @if (User.Identity.IsAuthenticated)
  11. {
  12. <li class="nav-item">
  13. @Html.ActionLink("List", "Index", "Employees", new { @class = "nav-link" })
  14. </li>
  15. <li class="nav-item">
  16. @Html.ActionLink("Add New", "Create", "Employees", new { @class = "nav-link" })
  17. </li>
  18. <li class="nav-item">
  19. @Html.ActionLink("Hello ->" + @User.Identity.Name, "", "", new { @class = "nav-link" })
  20. </li>
  21. <li class="nav-item">
  22. @Html.ActionLink("Logout", "Logout", "Account", new { @class = "nav-link" })
  23. </li>
  24. }
  25. else
  26. {
  27. <li class="nav-item">
  28. @Html.ActionLink("Login", "Login", "Account", new { @class = "nav-link" })
  29. </li>
  30. }
  31. </ul>
  32. </div>
  33. </nav>