Role Based Access Of An MVC Application

It means if you have some Admin related pages then only those users can access these pages that have Admin role.

For this here's the figure:
Admin role
                                                            Figure 1

Now open Visual Studio, then New Project.

new Project
                                                                           Figure 2

Internet application
                                                                  Figure 3

For User and Role I am going to use Application default database as in the following screenshot:

Application default database
                                                                           Figure 4

Now we will write code to manage role mean, Add new role, View All Role. Right click on Controllers folder and Add New Controller.

Add Controller
                                                                        Figure 5

mvc controller
                                                                     Figure 6

Add New Controller
                                                                     Figure 7

Now here in this RoleController write code to view and add new role. Here I will use ApplicationDbContext as in the following figure 4.

RoleController

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using RoleBasedAppAccess.Models;  
  7. using Microsoft.AspNet.Identity.EntityFramework;  
  8.   
  9. namespace RoleBasedAppAccess.Controllers  
  10. {  
  11.     public class RoleController : Controller  
  12.     {  
  13.         ApplicationDbContext context;  
  14.   
  15.         public RoleController()  
  16.         {  
  17.             context = new ApplicationDbContext();  
  18.         }  
  19.   
  20.         /// <summary>  
  21.         /// Get All Roles  
  22.         /// </summary>  
  23.         /// <returns></returns>  
  24.         public ActionResult Index()  
  25.         {  
  26.             var Roles = context.Roles.ToList();  
  27.             return View(Roles);  
  28.         }  
  29.   
  30.         /// <summary>  
  31.         /// Create  a New role  
  32.         /// </summary>  
  33.         /// <returns></returns>  
  34.         public ActionResult Create()  
  35.         {  
  36.             var Role = new IdentityRole();  
  37.             return View(Role);  
  38.         }  
  39.   
  40.         /// <summary>  
  41.         /// Create a New Role  
  42.         /// </summary>  
  43.         /// <param name="Role"></param>  
  44.         /// <returns></returns>  
  45.         [HttpPost]  
  46.         public ActionResult Create(IdentityRole Role)  
  47.         {  
  48.             context.Roles.Add(Role);  
  49.             context.SaveChanges();  
  50.             return RedirectToAction("Index");  
  51.         }  
  52.        
  53.     }  
  54. }  
Here I am using ASP.NET identity:

ASP.NET identity
                                          Figure 8

Now Add View on Index ActionMethod of RoleController:

Go to Views, then Role and Index.cshtml.
  1. @model IEnumerable<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>  
  2. @{  
  3.     ViewBag.Title = "Manage Role";  
  4. }  
  5. <h2>Manage Role</h2>  
  6. <table><tr><td style="height:20px;"></td></tr></table>  
  7. <table id="tbrole" style="width:30%; border:solid 4px red; background-color:skyblue; padding-left:10px;">  
  8.     <tr>  
  9.         <td style="background:green; color:white; padding:10px;">  
  10.             Role Name  
  11.         </td>  
  12.     </tr>  
  13.     @foreach (var item in Model)  
  14.     {  
  15.         <tr>  
  16.             <td style="padding:10px; border-bottom:1px solid #ff006e;">  
  17.                 @item.Name  
  18.             </td>  
  19.         </tr>  
  20.     }  
  21. </table>  
  22. <table>  
  23.     <tr><td style="height:20px;"></td></tr>  
  24.     <tr>  
  25.         <td style="height:20px; text-align:right;">  
  26.             @Html.ActionLink("Add New Role""Create""Role")  
  27.         </td>  
  28.     </tr>  
  29. </table>  
Add View on Index ActionMethod
                                                                              Figure 9

Now again right click on Create ActionMethod in RoleController, then click Add View.

Go to Views, then Role and Create.cshtml.
  1. @model Microsoft.AspNet.Identity.EntityFramework.IdentityRole  
  2. @{  
  3.     ViewBag.Title = "Add New Role";  
  4. }  
  5. <h2>Add New Role:</h2>  
  6. <style type="text/css">  
  7.     #tbrole, .c {  
  8.         border: double;  
  9.     }  
  10. </style>  
  11. @using (Html.BeginForm())  
  12. {  
  13.     <table style="width:40%; border:solid 4px red; background-color:skyblue; padding:10px;">  
  14.         <tr>  
  15.             <td style="background:green; color:white; padding:10px;">Role Name:</td>  
  16.             <td style="background:green; color:white; padding:10px;">  
  17.                 @Html.EditorFor(m => m.Name)  
  18.             </td>  
  19.         </tr>  
  20.         <tr><td style="height:20px;" colspan="2"></td></tr>  
  21.         <tr><td></td><td><input type="submit" value="Create Role" /></td></tr>  
  22.         <tr><td style="height:20px;" colspan="2"></td></tr>  
  23.     </table>  
  24. }  
Create ActionMethod
                                                                           Figure 10

Now open Views, then Shared and _Layout.cshtml
 
Add a link here to manage Role.
  1. <div class="navbar-collapse collapse">  
  2.    <ul class="nav navbar-nav">  
  3.       <li>@Html.ActionLink("Manage Role""Index""Role")</li>   
  4.    </ul>  
  5.    @Html.Partial("_LoginPartial")  
  6. </div>  
Now run you application:

run you application
                                                                           Figure 11

See Manage Role Menu and Click.

Manage Role Menu
                                                                        Figure 12

Click Add New Role

Click on Add New Role
                                                                           Figure 13

Enter your Role Name and click Create Role Button.

manage role
                                                                           Figure 14

See your available roles. Now I added one more role i.e.: User.

Now see these roles in your ASP.NET database.

show table data
                                                                           Figure 15

aspnetrole
                                                                           Figure 16

role name
                                                                       Figure 17

Now add users to your application, so now open Controller and go to AccountController.

Create an instance of ApplicationDbContext as in the following code snippet:
  1. ApplicationDbContext context;  
  2.   
  3. public AccountController()  
  4. {  
  5.    context = new ApplicationDbContext();  
  6. }  
Here while adding new user we will assign role to this user, so I am showing role in a dropdown list:
  1. // GET: /Account/Register  
  2. [AllowAnonymous]  
  3. public ActionResult Register()  
  4. {  
  5.     ViewBag.Name = new SelectList(context.Roles.ToList(), "Name""Name");  
  6.     return View();  
  7. }  
I made a change here in Register View and added a dropdown to select Role:

Go to My Views, then Account and Register.cshtml:
  1. @model RoleBasedAppAccess.Models.RegisterViewModel  
  2. @{  
  3.     ViewBag.Title = "Register";  
  4. }  
  5.   
  6. <h2>@ViewBag.Title.</h2>  
  7.   
  8. @using (Html.BeginForm("Register""Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))  
  9. {  
  10.     @Html.AntiForgeryToken()  
  11.     <h4>Create a new account.</h4>  
  12.     <hr />  
  13.     @Html.ValidationSummary(""new { @class = "text-danger" })  
  14.     <div class="form-group">  
  15.         @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })  
  16.         <div class="col-md-10">  
  17.             @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })  
  18.         </div>  
  19.     </div>  
  20.     <div class="form-group">  
  21.         @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })  
  22.         <div class="col-md-10">  
  23.             @Html.PasswordFor(m => m.Password, new { @class = "form-control" })  
  24.         </div>  
  25.     </div>  
  26.     <div class="form-group">  
  27.         @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })  
  28.         <div class="col-md-10">  
  29.             @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })  
  30.         </div>  
  31.     </div>  
  32.     <!--Select the Role Type for the User-->  
  33.     <div class="form-group">  
  34.         @Html.Label("Select Your User Type"new { @class = "col-md-2 control-label" })  
  35.         <div class="col-md-10">  
  36.             @*@Html.DropDownList("Name")*@  
  37.             @Html.DropDownList("Name", (SelectList)ViewBag.Name, "--Choose Role--")  
  38.         </div>  
  39.     </div>  
  40.     <!--Ends Here-->  
  41.   
  42.     <div class="form-group">  
  43.         <div class="col-md-offset-2 col-md-10">  
  44.             <input type="submit" class="btn btn-default" value="Register" />  
  45.         </div>  
  46.     </div>  
  47. }  
  48.   
  49. @section Scripts {  
  50.     @Scripts.Render("~/bundles/jqueryval")  
  51. }  
I updated Controller, then Account and Register.
  1. [HttpPost]  
  2. [AllowAnonymous]  
  3. [ValidateAntiForgeryToken]  
  4. public async Task<ActionResult> Register(RegisterViewModel model)  
  5. {  
  6.     if (ModelState.IsValid)  
  7.     {  
  8.         var user = new ApplicationUser { UserName = model.Email, Email = model.Email };  
  9.         var result = await UserManager.CreateAsync(user, model.Password);  
  10.         if (result.Succeeded)  
  11.         {  
  12.   
  13.             //Assign Role to user Here   
  14.             await this.UserManager.AddToRoleAsync(user.Id, model.Name);  
  15.             //Ends Here  
  16.   
  17.   
  18.             await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);  
  19.   
  20.             return RedirectToAction("Index""Home");  
  21.         }  
  22.         AddErrors(result);  
  23.     }  
  24.   
  25.     // If we got this far, something failed, redisplay form  
  26.     return View(model);  
  27. }  
Run your application and click Register:

Register
                                                                        Figure 18

Run your application
                                                                           Figure 19

Now again make a registration.

registration
                                                                           Figure 20

Now see your data in your Server Explorer:

AspNetUsers

data in AspNetUsers
                                                                           Figure 21

Server Explorer
                                                                        Figure 22

Now suppose we have 2 pages in my application. I want the Admin to access only Admin page and normal user can access User page. I am going to give link on header for these 2 pages.

So for this I am going to add a Folder, then CustomFilters and Add here a class-> AuthLogAttribute.cs and write the following code:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace RoleBasedAppAccess.CustomFilters  
  8. {  
  9.     public class AuthLogAttribute : AuthorizeAttribute  
  10.     {  
  11.         public AuthLogAttribute()  
  12.         {  
  13.             View = "AuthorizeFailed";  
  14.         }  
  15.   
  16.         public string View { getset; }  
  17.   
  18.         /// <summary>  
  19.         /// Check for Authorization  
  20.         /// </summary>  
  21.         /// <param name="filterContext"></param>  
  22.         public override void OnAuthorization(AuthorizationContext filterContext)  
  23.         {  
  24.             base.OnAuthorization(filterContext);  
  25.             IsUserAuthorized(filterContext);  
  26.         }  
  27.   
  28.         /// <summary>  
  29.         /// Method to check if the user is Authorized or not  
  30.         /// if yes continue to perform the action else redirect to error page  
  31.         /// </summary>  
  32.         /// <param name="filterContext"></param>  
  33.         private void IsUserAuthorized(AuthorizationContext filterContext)  
  34.         {  
  35.             // If the Result returns null then the user is Authorized   
  36.             if (filterContext.Result == null)  
  37.                 return;  
  38.   
  39.             //If the user is Un-Authorized then Navigate to Auth Failed View   
  40.             if (filterContext.HttpContext.User.Identity.IsAuthenticated)  
  41.             {  
  42.   
  43.                 // var result = new ViewResult { ViewName = View };  
  44.                 var vr = new ViewResult();  
  45.                 vr.ViewName = View;  
  46.   
  47.                 ViewDataDictionary dict = new ViewDataDictionary();  
  48.                 dict.Add("Message""Sorry you are not Authorized to View this Page");  
  49.   
  50.                 vr.ViewData = dict;  
  51.   
  52.                 var result = vr;  
  53.   
  54.                 filterContext.Result = result;  
  55.             }  
  56.         }  
  57.     }  
  58. }  
filterContext
                                                                        Figure 23

Now Add 2 Controllers: 1. Admin 2. Users.

Add view for both controller as in the following screenshot:

Add view
                                                   Figure 24

Now Set Access permission. Open Admin Controller and write the following code above your index action method:

method
                                                                        Figure 25

Controller-> Users:

Controller
                                                                              Figure 26

Now open Views, then Shared and click _Layout.cshtml. After that add link button to add Access to these 2 pages:
  1. <div class="navbar-collapse collapse">  
  2.    <ul class="nav navbar-nav">  
  3.        <li>@Html.ActionLink("Manage Role""Index""Role")</li>  
  4.        <li>@Html.ActionLink("ADMIN PAGE""Index""Admin")</li>  
  5.        <li>@Html.ActionLink("USER PAGE""Index""Users")</li>   
  6.    </ul>  
  7.    @Html.Partial("_LoginPartial")  
  8. </div>  
Now run the application:

run the application
                                                                        Figure 27

Click on ADMIN PAGE Link:

ADMIN PAGE
                                                                           Figure 28

You will redirect to login page. Now login with [email protected] which is in Admin Role.

login page
                                                                        Figure 29

Now click on USER PAGE as [email protected] is an ADMIN user and can’t access others Role page:

Role
                                                                           Figure 30

Now Login as [email protected] which is in User Role:

User Role
                                                                              Figure 31

If you try to access ADMIN PAGE, the following error message will be visible:

error
                                                                        Figure 32

 

Up Next
    Ebook Download
    View all
    Learn
    View all