Authentication and authorization using ASP.NET MVC (2024)

5 minute read

Step1: Select ASP.NET Web Application (.NET Framework)

Step2: Type project and solution name
Type project name as “MVCAuth” and also solution name as “MVC Auth”

Step 3: Select project template

  • Select project template as Web Application (Model-View-Controller)
  • Change authentication to Individual User Authentication
  • Click create button

Step 4: Change web.config file

<add name="DefaultConnection" connectionString="Data Source=localhost;Initial Catalog=AuthDB;Persist Security Info=False;User ID=sa; Password=mahedee.net; Pooling=False;MultipleActiveResultSets=False;Encrypt=False;TrustServerCertificate=False" providerName="System.Data.SqlClient" />

Step 5: Add some model and view model class

Step 6: Add Controllers to the application

  • Add RolesController in Controllers folder
  • Choose template MVC 5 Controller with read/write actions
  • Modify RolesController as follows
 public class RolesController : Controller { private ApplicationDbContext db = new ApplicationDbContext(); // GET: Roles public ActionResult Index() { var roleStore = new RoleStore<IdentityRole>(db); var roleManager = new RoleManager<IdentityRole>(roleStore); var roles = roleManager.Roles.ToList(); return View(roles); } // GET: Roles/Details/5 public ActionResult Details(int id) { return View(); } // GET: Roles/Create public ActionResult Create() { return View(); } // POST: Roles/Create [HttpPost] public ActionResult Create(IdentityRole role) { try { // TODO: Add insert logic here var roleStore = new RoleStore<IdentityRole>(db); var roleManager = new RoleManager<IdentityRole>(roleStore); if(!roleManager.RoleExists(role.Name)) { roleManager.Create(role); } return RedirectToAction("Index"); } catch { return View(); } } // GET: Roles/Edit/5 public ActionResult Edit(int id) { return View(); } // POST: Roles/Edit/5 [HttpPost] public ActionResult Edit(int id, FormCollection collection) { try { // TODO: Add update logic here return RedirectToAction("Index"); } catch { return View(); } } // GET: Roles/Delete/5 public ActionResult Delete(int id) { return View(); } // POST: Roles/Delete/5 [HttpPost] public ActionResult Delete(int id, FormCollection collection) { try { // TODO: Add delete logic here return RedirectToAction("Index"); } catch { return View(); } } }
  • Add UsersRoleController in Controllers folder
  • Choose template MVC 5 Controller with read/write actions
  • Modify UsersRoleController as follows
 public class UsersRoleController : Controller { ApplicationDbContext db = new ApplicationDbContext(); // GET: UsersRole public ActionResult Index() { List<UsersRolesVM> usersRolesVMs = new List<UsersRolesVM>(); List<ApplicationUser> users = db.Users.ToList(); var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)); foreach (ApplicationUser user in users) { UsersRolesVM usersRolesVM = new UsersRolesVM(); usersRolesVM.User = user; usersRolesVM.RoleNames = userManager.GetRoles(user.Id); usersRolesVMs.Add(usersRolesVM); } return View(usersRolesVMs); } // GET: UsersRole/Details/5 public ActionResult Details(int id) { return View(); } // GET: UsersRole/Create public ActionResult Create() { var roleStore = new RoleStore<IdentityRole>(db); var roleManager = new RoleManager<IdentityRole>(roleStore); var roles = roleManager.Roles.ToList(); ViewBag.UserId = new SelectList(db.Users.ToList(), "Id", "UserName"); ViewBag.RoleName = new SelectList(roles, "Name", "Name"); return View(); } // POST: UsersRole/Create [HttpPost] //public ActionResult Create(FormCollection collection) public ActionResult Create(UserRoleVM userRole) { try { if(userRole != null) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)); userManager.AddToRole(userRole.UserId, userRole.RoleName); } return RedirectToAction("Index"); } catch { return View(); } } // GET: UsersRole/Edit/5 public ActionResult Edit(int id) { return View(); } // POST: UsersRole/Edit/5 [HttpPost] public ActionResult Edit(int id, FormCollection collection) { try { // TODO: Add update logic here return RedirectToAction("Index"); } catch { return View(); } } // GET: UsersRole/Delete/5 public ActionResult Delete(int id) { return View(); } // POST: UsersRole/Delete/5 [HttpPost] public ActionResult Delete(int id, FormCollection collection) { try { // TODO: Add delete logic here return RedirectToAction("Index"); } catch { return View(); } } }

Step 7: Create Roles View to the application

  • Add Index View in Views->Roles folder
  • Add Create View in Views->Roles folder
  • Modify views as follows

Index.cshtml

@model IEnumerable<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>@{ ViewBag.Title = "Index";}<h2>Index</h2><p> @Html.ActionLink("Create New", "Create")</p><table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.Name) </th> <th></th> </tr>@foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.Id }) | @Html.ActionLink("Details", "Details", new { id=item.Id }) | @Html.ActionLink("Delete", "Delete", new { id=item.Id }) </td> </tr>}</table>

Create.cshtml

@*@model MVCAuth.Models.Role*@@model Microsoft.AspNet.Identity.EntityFramework.IdentityRole@{ ViewBag.Title = "Create";}<h2>Create</h2>@using (Html.BeginForm()){ @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Role</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> </div>}<div> @Html.ActionLink("Back to List", "Index")</div>@section Scripts { @Scripts.Render("~/bundles/jqueryval")}

Step 8: Create UsersRole View to the application

  • Add Index View in Views->UsersRole folder
  • Add Create View in Views->UsersRole folder
  • Modify views as follows

Index.cshtml

@model IEnumerable<MVCAuth.Models.UsersRolesVM>@{ ViewBag.Title = "Index";}<h2>Index</h2><p> @Html.ActionLink("Create New", "Create")</p><table class="table"> <tr> <th> @*@Html.DisplayNameFor(model => model.UserName)*@ User Name </th> <th> @*@Html.DisplayNameFor(model => model.RoleName)*@ Roles Name </th> <th></th> </tr> @foreach (var users in Model) { foreach (string rolesName in users.RoleNames) { <tr> <td> @Html.DisplayFor(modelItem => users.User.UserName) </td> <td> @Html.DisplayFor(modelItem => rolesName) </td> <td> @Html.ActionLink("Delete", "Delete", new { id = 1 }) </td> </tr> } }</table>

Create.cshtml

@model MVCAuth.Models.UserRoleVM@{ ViewBag.Title = "Create";}<h2>Create</h2>@using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>UserRoleVM</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.UserName, "UserName", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DropDownList("UserId", null, htmlAttributes: new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.RoleName, "RoleName", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DropDownList("RoleName", null, htmlAttributes: new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div></div>}<div> @Html.ActionLink("Back to List", "Index")</div>@section Scripts { @Scripts.Render("~/bundles/jqueryval")}

Step 9: Run migration command in package manager console

Now the application is ready to run.

Source Code

Authentication and authorization using ASP.NET MVC (2024)
Top Articles
Goal Setting in Four Steps for First-Gen College Students
HyperVerse Price Prediction - KoinX
Antisis City/Antisis City Gym
Lowe's Garden Fence Roll
Chris Provost Daughter Addie
Polyhaven Hdri
Wfin Local News
Craigslist Cars And Trucks Buffalo Ny
Noaa Weather Philadelphia
Corporate Homepage | Publix Super Markets
Tiger Island Hunting Club
Lesson 2 Homework 4.1
Degreeworks Sbu
Theycallmemissblue
Troy Athens Cheer Weebly
Craigslist Alabama Montgomery
Identogo Brunswick Ga
Flower Mound Clavicle Trauma
Hair Love Salon Bradley Beach
Dr. med. Uta Krieg-Oehme - Lesen Sie Erfahrungsberichte und vereinbaren Sie einen Termin
Apne Tv Co Com
Napa Autocare Locator
Everything We Know About Gladiator 2
Roll Out Gutter Extensions Lowe's
Csi Tv Series Wiki
Craigslist Houses For Rent In Milan Tennessee
Ice Dodo Unblocked 76
Phantom Fireworks Of Delaware Watergap Photos
Harrison 911 Cad Log
Best Town Hall 11
130Nm In Ft Lbs
Japanese Emoticons Stars
Jail Roster Independence Ks
Rlcraft Toolbelt
L'alternativa - co*cktail Bar On The Pier
Strange World Showtimes Near Atlas Cinemas Great Lakes Stadium 16
Help with your flower delivery - Don's Florist & Gift Inc.
Missouri State Highway Patrol Will Utilize Acadis to Improve Curriculum and Testing Management
1-800-308-1977
SOC 100 ONL Syllabus
Smith And Wesson Nra Instructor Discount
Anya Banerjee Feet
Compare Plans and Pricing - MEGA
Mvnt Merchant Services
Section 212 at MetLife Stadium
Convenient Care Palmer Ma
Cpmc Mission Bernal Campus & Orthopedic Institute Photos
Reese Witherspoon Wiki
Linkbuilding uitbesteden
The Horn Of Plenty Figgerits
Take Me To The Closest Ups
Kobe Express Bayside Lakes Photos
Latest Posts
Article information

Author: Eusebia Nader

Last Updated:

Views: 6021

Rating: 5 / 5 (80 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Eusebia Nader

Birthday: 1994-11-11

Address: Apt. 721 977 Ebert Meadows, Jereville, GA 73618-6603

Phone: +2316203969400

Job: International Farming Consultant

Hobby: Reading, Photography, Shooting, Singing, Magic, Kayaking, Mushroom hunting

Introduction: My name is Eusebia Nader, I am a encouraging, brainy, lively, nice, famous, healthy, clever person who loves writing and wants to share my knowledge and understanding with you.