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.
- create tabular array Employee
- (
- EmpIdint primary key identity (1,one),
- Name nvarchar(50),
- Genderchar (10),
- Ageint ,
- Position nvarchar(50),
- Office nvarchar(50),
- HireDate datetime,
- Salaryint ,
- DepartmentIdint
- )
- create tabular array Section
- (
- DeptIdint primary key identity(one,i),
- DepartmentName nvarchar(fifty)
- )
- create tabular array Users
- (
- Idint primary key identity(ane,i),
- Username nvarchar(l),
- Password nvarchar(50)
- )
- create tabular array Roles
- (
- Idint chief key identity(1,ane),
- RoleName nvarchar(50)
- )
- create table UserRoleMapping
- (
- Idint primary primal identity(i,1),
- UserIdint ,
- RoleIdint
- )
- alter table Employee Add together strange key
- (DepartmentId)references Department(DeptId)
- alter tabular array UserRoleMapping Add foreign central (UserId)
- references Users(Id)
- change table UserRoleMapping Add strange central (RoleId)
- 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.
Stride 4
Select "empty" template, check on the MVC box, and click OK.
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.
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".
After you click on "Add a window", the magician will open up. Cull EF Designer from the database and click "Next".
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".
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".
Afterward clicking on Adjacent, another window volition announced. Choose the database table proper noun every bit shown in the beneath screenshot and click "Terminate".
Entity Framework gets added and the respective class gets generated under the Models folder.
Step 6
Right-click on Controllers folder and add a controller.
A window volition announced. Choose MVC5 Controller with views, using Entity Framework and click "Add".
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.
Change Employees Controller Code
- using MvcRoleBasedAuthentication_Demo.Models;
- using Organization.Data.Entity;
- using Arrangement.Linq;
- using System.Net;
- using System.Web.Mvc;
- namespace MvcRoleBasedAuthentication_Demo.Controllers
- {
- public class EmployeesController : Controller
- {
- private EmployeeContext db = new EmployeeContext();
- [Authorize(Roles ="Admin,Employee" )]
- public ActionResult Index()
- {
- var employees = db.Employees.Include(e => e.Department);
- return View(employees.ToList());
- }
- [Authorize(Roles ="Admin,Employee" )]
- public ActionResult Details( int ? id)
- {
- if (id == null )
- {
- render new HttpStatusCodeResult(HttpStatusCode.BadRequest);
- }
- Employee employee = db.Employees.Notice(id);
- if (employee == cypher )
- {
- return HttpNotFound();
- }
- return View(employee);
- }
- [Authorize(Roles ="Employee" )]
- public ActionResult Create()
- {
- ViewBag.DepartmentId =new SelectList(db.Departments, "DeptId" , "DepartmentName" );
- return View();
- }
- [Authorize(Roles ="Employee" )]
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Create([Bind(Include = "EmpId,Proper name,Gender,Historic period,Position,Role,HireDate,Bacon,DepartmentId" )] Employee employee)
- {
- if (ModelState.IsValid)
- {
- db.Employees.Add(employee);
- db.SaveChanges();
- render RedirectToAction( "Index" );
- }
- ViewBag.DepartmentId =new SelectList(db.Departments, "DeptId" , "DepartmentName" , employee.DepartmentId);
- return View(employee);
- }
- [Authorize(Roles ="Employee" )]
- public ActionResult Edit( int ? id)
- {
- if (id == null )
- {
- return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
- }
- Employee employee = db.Employees.Find(id);
- if (employee == null )
- {
- render HttpNotFound();
- }
- ViewBag.DepartmentId =new SelectList(db.Departments, "DeptId" , "DepartmentName" , employee.DepartmentId);
- return View(employee);
- }
- [Authorize(Roles ="Employee" )]
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Edit([Bind(Include = "EmpId,Name,Gender,Historic period,Position,Office,HireDate,Salary,DepartmentId" )] Employee employee)
- {
- if (ModelState.IsValid)
- {
- db.Entry(employee).Country = EntityState.Modified;
- db.SaveChanges();
- render RedirectToAction( "Alphabetize" );
- }
- ViewBag.DepartmentId =new SelectList(db.Departments, "DeptId" , "DepartmentName" , employee.DepartmentId);
- return View(employee);
- }
- [Authorize(Roles ="Admin,Employee" )]
- public ActionResult Delete( int ? id)
- {
- if (id == null )
- {
- return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
- }
- Employee employee = db.Employees.Notice(id);
- if (employee == null )
- {
- return HttpNotFound();
- }
- render View(employee);
- }
- [Authorize(Roles ="Admin,Employee" )]
- [HttpPost, ActionName("Delete" )]
- [ValidateAntiForgeryToken]
- public ActionResult DeleteConfirmed( int id)
- {
- Employee employee = db.Employees.Find(id);
- db.Employees.Remove(employee);
- db.SaveChanges();
- return RedirectToAction( "Index" );
- }
- protected override void Dispose( bool disposing)
- {
- if (disposing)
- {
- db.Dispose();
- }
- base of operations .Dispose(disposing);
- }
- }
- }
Step six
Correct click on Models folder and create a UserRoleProvider class,
UserRoleProvider Grade
- using Organisation;
- using System.Linq;
- using System.Web.Security;
- namespace MvcRoleBasedAuthentication_Demo.Models
- {
- public class UserRoleProvider : RoleProvider
- {
- public override string ApplicationName
- {
- get
- {
- throw new NotImplementedException();
- }
- prepare
- {
- throw new NotImplementedException();
- }
- }
- public override void AddUsersToRoles( string [] usernames, cord [] roleNames)
- {
- throw new NotImplementedException();
- }
- public override void CreateRole( cord roleName)
- {
- throw new NotImplementedException();
- }
- public override bool DeleteRole( string roleName, bool throwOnPopulatedRole)
- {
- throw new NotImplementedException();
- }
- public override cord [] FindUsersInRole( cord roleName, string usernameToMatch)
- {
- throw new NotImplementedException();
- }
- public override cord [] GetAllRoles()
- {
- throw new NotImplementedException();
- }
- public override cord [] GetRolesForUser( string username)
- {
- using (EmployeeContext _Context= new EmployeeContext())
- {
- var userRoles = (from userin _Context.Users
- join roleMappingin _Context.UserRoleMappings
- on user.Id equals roleMapping.UserId
- bring together partin _Context.Roles
- on roleMapping.RoleId equals role.Id
- where user.Username == username
- select role.RoleName).ToArray();
- render userRoles;
- }
- }
- public override string [] GetUsersInRole( string roleName)
- {
- throw new NotImplementedException();
- }
- public override bool IsUserInRole( string username, string roleName)
- {
- throw new NotImplementedException();
- }
- public override void RemoveUsersFromRoles( string [] usernames, string [] roleNames)
- {
- throw new NotImplementedException();
- }
- public override bool RoleExists( cord roleName)
- {
- throw new NotImplementedException();
- }
- }
- }
Footstep 7
Open web config file and write the following code.
- <authentication fashion= "Forms" >
- <forms loginUrl="Account/Login" ></forms>
- </authentication>
- <roleManager defaultProvider="userRoleProvider" enabled= "true" >
- <providers>
- <articulate/>
- <add together name="userRoleProvider" type= "MvcRoleBasedAuthentication_Demo.Models.UserRoleProvider" />
- </providers>
- </roleManager>
Stride viii
Open _Layout.cshtml file which under views binder in shared folder.
- <nav class = "navbar navbar-aggrandize-physician bg-dark navbar-nighttime" >
- <aform = "navbar-brand" href= "#" >
- @Html.ActionLink("Awarding proper name" , "Index" , "Home" , new { area = "" }, new { @ class = "navbar-brand" })
- </a>
- <buttonclass = "navbar-toggler" type= "push button" information-toggle= "plummet" data-target= "#collapsibleNavbar" >
- <bridgeclass = "navbar-toggler-icon" ></span>
- </push>
- <divform = "collapse navbar-collapse" id= "collapsibleNavbar" >
- <ulclass = "navbar-nav" >
- @if (User.Identity.IsAuthenticated)
- {
- <liclass = "nav-item" >
- @Html.ActionLink("List" , "Alphabetize" , "Employees" , new { @ grade = "nav-link" })
- </li>
- <liclass = "nav-item" >
- @Html.ActionLink("Add New" , "Create" , "Employees" , new { @ course = "nav-link" })
- </li>
- <liclass = "nav-item" >
- @Html.ActionLink("Hello ->" + @User.Identity.Name, "" , "" , new { @ grade = "nav-link" })
- </li>
- <liclass = "nav-item" >
- @Html.ActionLink("Logout" , "Logout" , "Business relationship" , new { @ class = "nav-link" })
- </li>
- }
- else
- {
- <ligrade = "nav-item" >
- @Html.ActionLink("Login" , "Login" , "Business relationship" , new { @ class = "nav-link" })
- </li>
- }
- </ul>
- </div>
- </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