Email: Password:       Forgot Password 
    .netCodeSG
A Saarsha Group Online Community for dot net codes group like C#, Asp.NET, VB.NET, Sharepoint, JavaScript, JQuery, Ajax, SQL, WCF, WPF.
 
TECHNOLOGIES:
 

Role Based Access of a MVC Application

Article:
Viewed:  2227 
Posted On:  9/13/2015 4:10:21 AM 
How we can make role based access of pages in an application? 

In this article I am going to show how we can give role based access to our application. Mean if you have some Admin related pages then only those users can access these pages that have Admin role.

For this see below image:

1.png

Image 1.

Now open visual studio -> New Project ->

2.png

Image 2.

3.png

Image 3.

For User and Role I am going to use Application default database as shown below:

4.png

Image 4.

Now we will write code to manage role mean Add new role, View All Role. So right click on Controller folder-> Add New Controller.

5.png

Image 5.

6.png

Image 6.

7.png

Image 7.

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

RoleController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RoleBasedAppAccess.Models;
using Microsoft.AspNet.Identity.EntityFramework;
 
namespace RoleBasedAppAccess.Controllers
{
    public class RoleController : Controller
    {
        ApplicationDbContext context;
 
        public RoleController()
        {
            context = new ApplicationDbContext();
        }
 
        /// <summary>
        /// Get All Roles
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            var Roles = context.Roles.ToList();
            return View(Roles);
        }
 
        /// <summary>
        /// Create  a New role
        /// </summary>
        /// <returns></returns>
        public ActionResult Create()
        {
            var Role = new IdentityRole();
            return View(Role);
        }
 
        /// <summary>
        /// Create a New Role
        /// </summary>
        /// <param name="Role"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(IdentityRole Role)
        {
            context.Roles.Add(Role);
            context.SaveChanges();
            return RedirectToAction("Index");
        }
  
    }
}

Here I am using ASP.NET identity:

8.png

Image 8.

Now Add View on Index ActionMethod of RoleController:

So my Views-> Role-> Index.cshtml

@model IEnumerable<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>
@{
    ViewBag.Title = "Manage Role";
}
<h2>Manage Role</h2>
<table><tr><td style="height:20px;"></td></tr></table>
<table id="tbrole" style="width:30%border:solid 4px redbackground-color:skybluepadding-left:10px;">
    <tr>
        <td style="background:greencolor:whitepadding:10px;">
            Role Name
        </td>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td style="padding:10pxborder-bottom:1px solid #ff006e;">
                @item.Name
            </td>
        </tr>
    }
</table>
<table>
    <tr><td style="height:20px;"></td></tr>
    <tr>
        <td style="height:20pxtext-align:right;">
            @Html.ActionLink("Add New Role""Create""Role")
        </td>
    </tr>
</table>

9.png 

Image 9.

Now Again Right click on Create ActionMethod in RoleController-> Add View->

So my Views-> Role-> Create.cshtml

@model Microsoft.AspNet.Identity.EntityFramework.IdentityRole
@{
    ViewBag.Title = "Add New Role";
}
<h2>Add New Role:</h2>
<style type="text/css">
    #tbrole.c {
        borderdouble;
    }
</style>
@using (Html.BeginForm())
{
    <table style="width:40%border:solid 4px redbackground-color:skybluepadding:10px;">
        <tr>
            <td style="background:greencolor:whitepadding:10px;">Role Name:</td>
            <td style="background:greencolor:whitepadding:10px;">
                @Html.EditorFor(m => m.Name)
            </td>
        </tr>
        <tr><td style="height:20px;" colspan="2"></td></tr>
        <tr><td></td><td><input type="submit" value="Create Role" /></td></tr>
        <tr><td style="height:20px;" colspan="2"></td></tr>
    </table>
}

10.png

Image 10.

Now open Views-> Shared-> _Layout.cshtml and Add a link here to manage Role

<div class="navbar-collapse collapse">
   <ul class="nav navbar-nav">
          <li>@Html.ActionLink("Manage Role""Index""Role")</li>                  
      </ul>
      @Html.Partial("_LoginPartial")
 </div>

Now run you application:

11.png

Image 11.

See here Manage Role Menu-> Click

12.png

Image 12.

Click on Add New Role

13.png

Image 13.

Enter your Role Name and click on Create Role Button.

14.png

Image 14.

See your all available roles. Now I added one more role ie: User.

Now see these roles in your asp.net data base.

15.png

Image 15.

16.png

Image 16.

17.png

Image 17.

Now time to add users to you application: So now open Controller -> AccountController. -> Create a instance of ApplicationDbContext like below:

ApplicationDbContext context;
 
public AccountController()
{
   context = new ApplicationDbContext();
}

Here while adding new user we will assign role to this user. So I am showing role in a drop down list:
 
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
    ViewBag.Name = new SelectList(context.Roles.ToList(), "Name""Name");
    return View();
}

I made a change here in Register View-> I added a drop down to select Role:

My Views-> Account-> Register.cshtml:

@model RoleBasedAppAccess.Models.RegisterViewModel
@{
    ViewBag.Title = "Register";
}
 
<h2>@ViewBag.Title.</h2>
 
@using (Html.BeginForm("Register""Account"FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <h4>Create a new account.</h4>
    <hr />
    @Html.ValidationSummary(""new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
        </div>
    </div>
    <!--Select the Role Type for the User-->
    <div class="form-group">
        @Html.Label("Select Your User Type"new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @*@Html.DropDownList("Name")*@
            @Html.DropDownList("Name", (SelectList)ViewBag.Name, "--Choose Role--")
        </div>
    </div>
    <!--Ends Here-->
 
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Register" />
        </div>
    </div>
}
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
 

I updated Controller-> Account-> Register

[HttpPost]
[AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                   //Assign Role to user Here
                    await this.UserManager.AddToRoleAsync(user.Id, model.Name);
                    //Ends Here
                    await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                    return RedirectToAction("Index""Home");
                }
                AddErrors(result);
            }
            // If we got this far, something failed, redisplay form
            return View(model);

        }

Run your application and click on Register:

18.png

Image 18.

19.png

Image 19.

Now again make a registration.

20.png

Image 20.

Now see your data in your Server Explorer->

AspNetUsers

21.png

Image 21.

22.png

Image 22.

Now suppose we have 2 page in my application. I want that Admin can 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 -> CustomFilters -> Add here a class-> AuthLogAttribute.cs-> and do the below code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace RoleBasedAppAccess.CustomFilters
{
    public class AuthLogAttribute : AuthorizeAttribute
    {
        public AuthLogAttribute()
        {
            View = "AuthorizeFailed";
        }
 
        public string View { getset; }
 
        /// <summary>
        /// Check for Authorization
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            IsUserAuthorized(filterContext);
        }
 
        /// <summary>
        /// Method to check if the user is Authorized or not
        /// if yes continue to perform the action else redirect to error page
        /// </summary>
        /// <param name="filterContext"></param>
        private void IsUserAuthorized(AuthorizationContext filterContext)
        {
            // If the Result returns null then the user is Authorized
            if (filterContext.Result == null)
                return;
 
            //If the user is Un-Authorized then Navigate to Auth Failed View
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
 
                // var result = new ViewResult { ViewName = View };
                var vrER = new ViewResult();
                vrER .ViewName = View;
 
                ViewDataDictionary dict = new ViewDataDictionary();
                dict.Add("Message""Sorry you are not Authorized to View this Page");
 
                vrER .ViewData = dict;
 
                var result = vrER ;
 
                filterContext.Result = result;
            }
        }
    }
}

23.png

Image 23.

Now Add 2 Controller -> 1. Admin 2. Users

Add view for both controller. Like Below:

24.png

Image 24.

Now Set Access permission. So open Admin Controller and do below code above your index action method:

25.png

Image 25.

Controller-> Users:

26.png

Image 26.

Now open Views-> Shared-> _Layout.cshtml and add link button to add Access these 2 pages:

<div class="navbar-collapse collapse">
   <ul class="nav navbar-nav">
       <li>@Html.ActionLink("Manage Role""Index""Role")</li>
       <li>@Html.ActionLink("ADMIN PAGE""Index""Admin")</li>
       <li>@Html.ActionLink("USER PAGE""Index""Users")</li>
   </ul>
   @Html.Partial("_LoginPartial")
</div>
 

Now run the application :

27.png

Image 27.

Click on ADMIN PAGE Link:

28.png

Image 28.

You will redirect to login page. Now login with rahul@rahul.com which is in Admin Role.

29.png

Image 29.

Now click on USER PAGE -> As rahul@rahul.com is an ADMIN user and can't access others Role page:

30.png

Image 30.

Now Login as abhishek@abhishek.com which is in User Role:


31.png

Image 31.

If you try to access ADMIN Page now then you will get error message.

32.png

Image 32.

  Comment:
         HOME   |   Submit Article   |   Contact Us   |   About Us   |   Terms & Condition   |   Advertise With us