banner



Simple and Easy Mvc Login With Multiple Role Updated FREE

Simple and Easy Mvc Login With Multiple Role

Introduction

This article will explain the role-based hallmark in ASP.Cyberspace MVC, with examples. I strongly recommended reading my previous manufactures before proceeding to this article as it is a continuation function of my previous commodity.

  • Authentication And Authorization In Asp.Net MVC
  • Authority Filter In Asp.Net MVC
  • Forms Authentication In ASP.Internet MVC

Step one

Open your favourite SQL Server database with any version. Information technology really doesn't matter what version it is. Create the following database data tables.

  1. create tabular array  Employee
  2. (
  3.    EmpIdint primary key  identity (1,one),
  4.    Name  nvarchar(50),
  5.    Genderchar (10),
  6.    Ageint ,
  7.    Position nvarchar(50),
  8.    Office nvarchar(50),
  9.    HireDate datetime,
  10.    Salaryint ,
  11.    DepartmentIdint
  12. )
  13. create tabular array  Section
  14. (
  15.    DeptIdint primary key  identity(one,i),
  16.    DepartmentName nvarchar(fifty)
  17. )
  18. create tabular array  Users
  19. (
  20.    Idint primary key  identity(ane,i),
  21.    Username nvarchar(l),
  22.    Password  nvarchar(50)
  23. )
  24. create tabular array  Roles
  25. (
  26.    Idint chief key  identity(1,ane),
  27.    RoleName nvarchar(50)
  28. )
  29. create table  UserRoleMapping
  30. (
  31.    Idint primary primal  identity(i,1),
  32.    UserIdint ,
  33.    RoleIdint
  34. )
  35. alter table  Employee Add together strange key
  36. (DepartmentId)references  Department(DeptId)
  37. alter tabular array  UserRoleMapping Add foreign central (UserId)
  38. references  Users(Id)
  39. change table  UserRoleMapping Add strange central (RoleId)
  40. references  Roles(id)

Step two

Open Visual Studio 2015 or an editor of your pick and create a new project.

Step three

Choose "spider web application" project and give an appropriate proper noun to your project.

Role Based Authentication In ASP.NET MVC

Stride 4

Select "empty" template, check on the MVC box, and click OK.

Role Based Authentication In ASP.NET MVC

Step five

Right-click on the Models folder and add together a database model. Add Entity Framework now. For that, right-click on Models folder, select Add together, then select New Detail.

Role Based Authentication In ASP.NET MVC

You will get a window; from there, select Data from the left console and choose ADO.NET Entity Information Model, give information technology the proper name EmployeeModel (this proper noun is not mandatory, you lot tin can requite any name) and click "Add together".

Role Based Authentication In ASP.NET MVC

After you click on "Add a window", the magician will open up. Cull EF Designer from the database and click "Next".

Role Based Authentication In ASP.NET MVC

Later on clicking on "Next", a window will announced. Choose New Connection. Another window will appear. Add your server name - if information technology is local, and so enter a dot (.). Choose your database and click "OK".

Role Based Authentication In ASP.NET MVC

The connection will be added. If you wish, relieve the connection proper noun equally you want. You can alter the name of your connection below. It volition save the connectedness in the web config. At present, click "Next".

Role Based Authentication In ASP.NET MVC

Afterward clicking on Adjacent, another window volition announced. Choose the database table proper noun every bit shown in the beneath screenshot and click "Terminate".

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 volition announced. Choose MVC5 Controller with views, using Entity Framework and click "Add".

Role Based Authentication In ASP.NET MVC

After clicking on "Add together", another window will appear. Choose Model Class and data context course and click "Add together". The EmployeesController will be added under theControllers folder with corresponding views.

Role Based Authentication In ASP.NET MVC

Change Employees Controller Code

  1. using  MvcRoleBasedAuthentication_Demo.Models;
  2. using  Organization.Data.Entity;
  3. using  Arrangement.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. render new  HttpStatusCodeResult(HttpStatusCode.BadRequest);
  23.             }
  24.             Employee employee = db.Employees.Notice(id);
  25. if  (employee == cypher )
  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,Proper name,Gender,Historic period,Position,Role,HireDate,Bacon,DepartmentId" )] Employee employee)
  41.         {
  42. if  (ModelState.IsValid)
  43.             {
  44.                 db.Employees.Add(employee);
  45.                 db.SaveChanges();
  46. render  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. render  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,Historic period,Position,Office,HireDate,Salary,DepartmentId" )] Employee employee)
  70.         {
  71. if  (ModelState.IsValid)
  72.             {
  73.                 db.Entry(employee).Country = EntityState.Modified;
  74.                 db.SaveChanges();
  75. render  RedirectToAction( "Alphabetize" );
  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.Notice(id);
  88. if  (employee == null )
  89.             {
  90. return  HttpNotFound();
  91.             }
  92. render  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 of operations .Dispose(disposing);
  111.         }
  112.     }
  113. }

Step six

Correct click on Models folder and create a UserRoleProvider class,

Role Based Authentication In ASP.NET MVC

Role Based Authentication In ASP.NET MVC

UserRoleProvider Grade

  1. using  Organisation;
  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. prepare
  15.             {
  16. throw new  NotImplementedException();
  17.             }
  18.         }
  19. public override void  AddUsersToRoles( string [] usernames, cord [] roleNames)
  20.         {
  21. throw new  NotImplementedException();
  22.         }
  23. public override void  CreateRole( cord  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 cord [] FindUsersInRole( cord  roleName, string  usernameToMatch)
  32.         {
  33. throw new  NotImplementedException();
  34.         }
  35. public override cord [] GetAllRoles()
  36.         {
  37. throw new  NotImplementedException();
  38.         }
  39. public override cord [] GetRolesForUser( string  username)
  40.         {
  41. using  (EmployeeContext _Context= new  EmployeeContext())
  42.             {
  43.                 var userRoles = (from userin  _Context.Users
  44.                                  join roleMappingin  _Context.UserRoleMappings
  45.                                  on user.Id equals roleMapping.UserId
  46.                                  bring together partin  _Context.Roles
  47.                                  on roleMapping.RoleId equals role.Id
  48.                                  where user.Username == username
  49.                                  select role.RoleName).ToArray();
  50. render  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( cord  roleName)
  66.         {
  67. throw new  NotImplementedException();
  68.         }
  69.     }
  70. }

Footstep 7

Open web config file and write the following code.

  1. <authentication fashion= "Forms" >
  2.       <forms loginUrl="Account/Login" ></forms>
  3.     </authentication>
  4.     <roleManager defaultProvider="userRoleProvider"  enabled= "true" >
  5.       <providers>
  6.         <articulate/>
  7.         <add together name="userRoleProvider"  type= "MvcRoleBasedAuthentication_Demo.Models.UserRoleProvider" />
  8.       </providers>
  9.     </roleManager>

Stride viii

Open _Layout.cshtml file which under views binder in shared folder.

  1. <nav class = "navbar navbar-aggrandize-physician bg-dark navbar-nighttime" >
  2.         <aform = "navbar-brand"  href= "#" >
  3.             @Html.ActionLink("Awarding proper name" , "Index" , "Home" , new  { area = ""  }, new  { @ class  = "navbar-brand"  })
  4.         </a>
  5.         <buttonclass = "navbar-toggler"  type= "push button"  information-toggle= "plummet"  data-target= "#collapsibleNavbar" >
  6.             <bridgeclass = "navbar-toggler-icon" ></span>
  7.         </push>
  8.         <divform = "collapse navbar-collapse"  id= "collapsibleNavbar" >
  9.             <ulclass = "navbar-nav" >
  10.                 @if  (User.Identity.IsAuthenticated)
  11.                 {
  12.                     <liclass = "nav-item" >
  13.                         @Html.ActionLink("List" , "Alphabetize" , "Employees" , new  { @ grade  = "nav-link"  })
  14.                     </li>
  15.                     <liclass = "nav-item" >
  16.                         @Html.ActionLink("Add New" , "Create" , "Employees" , new  { @ course  = "nav-link"  })
  17.                     </li>
  18.                     <liclass = "nav-item" >
  19.                         @Html.ActionLink("Hello ->"  + @User.Identity.Name, "" , "" , new  { @ grade  = "nav-link"  })
  20.                     </li>
  21.                     <liclass = "nav-item" >
  22.                         @Html.ActionLink("Logout" , "Logout" , "Business relationship" , new  { @ class  = "nav-link"  })
  23.                     </li>
  24.                 }
  25. else
  26.                 {
  27.                     <ligrade = "nav-item" >
  28.                         @Html.ActionLink("Login" , "Login" , "Business relationship" , new  { @ class  = "nav-link"  })
  29.                     </li>
  30.                 }
  31.             </ul>
  32.         </div>
  33.     </nav>

Simple and Easy Mvc Login With Multiple Role

DOWNLOAD HERE

Source: https://www.c-sharpcorner.com/article/role-based-authentication-in-asp-net-mvc/

Posted by: delafuentelaregrell.blogspot.com

0 Response to "Simple and Easy Mvc Login With Multiple Role Updated FREE"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel