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. namespace RoleBasedAppAccess.Controllers
  9. {
  10. public class RoleController : Controller
  11. {
  12. ApplicationDbContext context;
  13. public RoleController()
  14. {
  15. context = new ApplicationDbContext();
  16. }
  17. /// <summary>
  18. /// Get All Roles
  19. /// </summary>
  20. /// <returns></returns>
  21. public ActionResult Index()
  22. {
  23. var Roles = context.Roles.ToList();
  24. return View(Roles);
  25. }
  26. /// <summary>
  27. /// Create a New role
  28. /// </summary>
  29. /// <returns></returns>
  30. public ActionResult Create()
  31. {
  32. var Role = new IdentityRole();
  33. return View(Role);
  34. }
  35. /// <summary>
  36. /// Create a New Role
  37. /// </summary>
  38. /// <param name="Role"></param>
  39. /// <returns></returns>
  40. [HttpPost]
  41. public ActionResult Create(IdentityRole Role)
  42. {
  43. context.Roles.Add(Role);
  44. context.SaveChanges();
  45. return RedirectToAction("Index");
  46. }
  47. }
  48. }
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. public AccountController()
  3. {
  4. context = new ApplicationDbContext();
  5. }
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. <h2>@ViewBag.Title.</h2>
  6. @using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
  7. {
  8. @Html.AntiForgeryToken()
  9. <h4>Create a new account.</h4>
  10. <hr />
  11. @Html.ValidationSummary("", new { @class = "text-danger" })
  12. <div class="form-group">
  13. @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
  14. <div class="col-md-10">
  15. @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
  16. </div>
  17. </div>
  18. <div class="form-group">
  19. @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
  20. <div class="col-md-10">
  21. @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
  22. </div>
  23. </div>
  24. <div class="form-group">
  25. @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
  26. <div class="col-md-10">
  27. @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
  28. </div>
  29. </div>
  30. <!--Select the Role Type for the User-->
  31. <div class="form-group">
  32. @Html.Label("Select Your User Type", new { @class = "col-md-2 control-label" })
  33. <div class="col-md-10">
  34. @*@Html.DropDownList("Name")*@
  35. @Html.DropDownList("Name", (SelectList)ViewBag.Name, "--Choose Role--")
  36. </div>
  37. </div>
  38. <!--Ends Here-->
  39. <div class="form-group">
  40. <div class="col-md-offset-2 col-md-10">
  41. <input type="submit" class="btn btn-default" value="Register" />
  42. </div>
  43. </div>
  44. }
  45. @section Scripts {
  46. @Scripts.Render("~/bundles/jqueryval")
  47. }
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. //Assign Role to user Here
  13. await this.UserManager.AddToRoleAsync(user.Id, model.Name);
  14. //Ends Here
  15. await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
  16. return RedirectToAction("Index", "Home");
  17. }
  18. AddErrors(result);
  19. }
  20. // If we got this far, something failed, redisplay form
  21. return View(model);
  22. }
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. namespace RoleBasedAppAccess.CustomFilters
  7. {
  8. public class AuthLogAttribute : AuthorizeAttribute
  9. {
  10. public AuthLogAttribute()
  11. {
  12. View = "AuthorizeFailed";
  13. }
  14. public string View { get; set; }
  15. /// <summary>
  16. /// Check for Authorization
  17. /// </summary>
  18. /// <param name="filterContext"></param>
  19. public override void OnAuthorization(AuthorizationContext filterContext)
  20. {
  21. base.OnAuthorization(filterContext);
  22. IsUserAuthorized(filterContext);
  23. }
  24. /// <summary>
  25. /// Method to check if the user is Authorized or not
  26. /// if yes continue to perform the action else redirect to error page
  27. /// </summary>
  28. /// <param name="filterContext"></param>
  29. private void IsUserAuthorized(AuthorizationContext filterContext)
  30. {
  31. // If the Result returns null then the user is Authorized
  32. if (filterContext.Result == null)
  33. return;
  34. //If the user is Un-Authorized then Navigate to Auth Failed View
  35. if (filterContext.HttpContext.User.Identity.IsAuthenticated)
  36. {
  37. // var result = new ViewResult { ViewName = View };
  38. var vr = new ViewResult();
  39. vr.ViewName = View;
  40. ViewDataDictionary dict = new ViewDataDictionary();
  41. dict.Add("Message", "Sorry you are not Authorized to View this Page");
  42. vr.ViewData = dict;
  43. var result = vr;
  44. filterContext.Result = result;
  45. }
  46. }
  47. }
  48. }
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