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:
Figure 1
Now open Visual Studio, then New Project.
Figure 2
Figure 3
For User and Role I am going to use Application default database as in the following screenshot:
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.
Figure 5
Figure 6
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
- 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();
- }
-
-
-
-
-
- public ActionResult Index()
- {
- var Roles = context.Roles.ToList();
- return View(Roles);
- }
-
-
-
-
-
- public ActionResult Create()
- {
- var Role = new IdentityRole();
- return View(Role);
- }
-
-
-
-
-
-
- [HttpPost]
- public ActionResult Create(IdentityRole Role)
- {
- context.Roles.Add(Role);
- context.SaveChanges();
- return RedirectToAction("Index");
- }
-
- }
- }
Here I am using ASP.NET identity:
Figure 8 Now Add View on Index ActionMethod of RoleController:
Go to Views, then Role and 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 red; background-color:skyblue; padding-left:10px;">
- <tr>
- <td style="background:green; color:white; padding:10px;">
- Role Name
- </td>
- </tr>
- @foreach (var item in Model)
- {
- <tr>
- <td style="padding:10px; border-bottom:1px solid #ff006e;">
- @item.Name
- </td>
- </tr>
- }
- </table>
- <table>
- <tr><td style="height:20px;"></td></tr>
- <tr>
- <td style="height:20px; text-align:right;">
- @Html.ActionLink("Add New Role", "Create", "Role")
- </td>
- </tr>
- </table>
Figure 9 Now again right click on Create ActionMethod in RoleController, then click Add View.
Go to Views, then Role and Create.cshtml.
- @model Microsoft.AspNet.Identity.EntityFramework.IdentityRole
- @{
- ViewBag.Title = "Add New Role";
- }
- <h2>Add New Role:</h2>
- <style type="text/css">
- #tbrole, .c {
- border: double;
- }
- </style>
- @using (Html.BeginForm())
- {
- <table style="width:40%; border:solid 4px red; background-color:skyblue; padding:10px;">
- <tr>
- <td style="background:green; color:white; padding:10px;">Role Name:</td>
- <td style="background:green; color:white; padding: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>
- }
Figure 10 Now open Views, then Shared and _Layout.cshtml
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:
Figure 11 See
Manage Role Menu and Click.
Figure 12 Click
Add New Role Figure 13 Enter your
Role Name and click Create Role Button.
Figure 14 See your available roles. Now I added one more role i.e.: User.
Now see these roles in your ASP.NET database.
Figure 15 Figure 16 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:
- 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 dropdown list:
-
- [AllowAnonymous]
- public ActionResult Register()
- {
- ViewBag.Name = new SelectList(context.Roles.ToList(), "Name", "Name");
- return View();
- }
I made a change here in Register View and added a dropdown to select Role:
Go to My Views, then Account and 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, then Account and 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)
- {
-
-
- await this.UserManager.AddToRoleAsync(user.Id, model.Name);
-
-
-
- await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
-
- return RedirectToAction("Index", "Home");
- }
- AddErrors(result);
- }
-
-
- return View(model);
- }
Run your application and click
Register:
Figure 18 Figure 19 Now again make a registration.
Figure 20 Now see your data in your Server Explorer:
AspNetUsers Figure 21
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:
- 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 { get; set; }
-
-
-
-
-
- public override void OnAuthorization(AuthorizationContext filterContext)
- {
- base.OnAuthorization(filterContext);
- IsUserAuthorized(filterContext);
- }
-
-
-
-
-
-
- private void IsUserAuthorized(AuthorizationContext filterContext)
- {
-
- if (filterContext.Result == null)
- return;
-
-
- if (filterContext.HttpContext.User.Identity.IsAuthenticated)
- {
-
-
- var vr = new ViewResult();
- vr.ViewName = View;
-
- ViewDataDictionary dict = new ViewDataDictionary();
- dict.Add("Message", "Sorry you are not Authorized to View this Page");
-
- vr.ViewData = dict;
-
- var result = vr;
-
- filterContext.Result = result;
- }
- }
- }
- }
Figure 23 Now Add 2 Controllers: 1. Admin 2. Users.
Add view for both controller as in the following screenshot:
Figure 24 Now Set Access permission. Open Admin Controller and write the following code above your index action method:
Figure 25 Controller-> Users:
Figure 26 Now open Views, then Shared and click _Layout.cshtml. After that add link button to add Access to 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:
Figure 27 Click on
ADMIN PAGE Link:
Figure 28 You will redirect to login page. Now login with
[email protected] which is in Admin Role.
Figure 29 Now click on
USER PAGE as
[email protected] is an ADMIN user and can’t access others Role page:
Figure 30 Now Login as
[email protected] which is in User Role:
Figure 31 If you try to access
ADMIN PAGE, the following error message will be visible:
Figure 32