Introduction
This article will explain the custom authentication filter in ASP.NET MVC. I will discuss with an example. Authentication filter was introduced in ASP.NET MVC 5 and provides great improvement for authenticating a user. As of now, there is no in-built authentication filter in MVC. So, if you want to use authentication filter, then the one and only way is to create a custom authentication filter and use that filter in your application. I suggest you please read the following series of articles for better understanding.
The real reason behind Authentication Filters?
Before the introduction of authentication filter in ASP.NET MVC, we developers used authorization filter for two different purposes - authentication and authorization. It was convenient because authorization filters were executed before executing any other action filters. For example, before executing the actual action method, we can use an authorization filter to redirect an unauthenticated user to a login page or some error page.
But now, we can separate the authentication-related tasks to a new custom authentication filter and perform the authorization related tasks using the authorization filters only. So, in simple words, we can say it is basically about the separation of concerns which will provide the developers with a focus on one aspect using one filter only.
Create Custom Authentication Filter in ASP.NET MVC?
To create a custom authentication filter in ASP.NET MVC, we need to create a class by implementing the IAuthenticationFilter Interface. This IAuthenticationFilter interface has 2 methods.
- OnAuthentication
- OnAuthenticationChallege
Step 1
Open Visual Studio 2015 or an editor of your choice and create a new project.
Step 2
Choose the "web application" project and give an appropriate name to your project.
Step 3
Select the "empty" template, check on the MVC box and click OK.
Step 4
Right-click on the Models folder and add a database model. Add Entity Framework now. For that, right-click on Models folder, select Add, then select New Item.
You will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name EmployeeModel (this name is not mandatory, you can give any name) and click "Add"
After you click on "Add a window", the wizard will open. Choose EF Designer from the database and click "Next".
After clicking on "Next", a window will appear. Choose New Connection. Another window will appear. Add your server name - if it is local, then enter a dot (.). Choose your database and click "OK".
The connection will be added. If you wish, save the connection name as you want. You can change the name of your connection below. It will save the connection in the web config. Now, click "Next".
After clicking on NEXT, another window will appear. Choose the database table name as shown in the below screenshot and click "Finish".
Entity Framework gets added and the respective class gets generated under the Models folder.
Step 5
Right-click on Controllers folder add a controller.
A window will appear. Choose MVC5 Controller with views, using Entity Framework and click "Add".
After clicking on "Add", another window will appear choose Model Class and data context class and click "Add". The EmployeesController will be added under the Controllers folder with respective views and views folder create details, edit and delete.
Modify Employees Controller Code
- using MvcRoleBasedAuthentication_Demo.Models;
- using System.Data.Entity;
- using System.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)
- {
- return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
- }
- Employee employee = db.Employees.Find(id);
- if (employee == null)
- {
- 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,Name,Gender,Age,Position,Office,HireDate,Salary,DepartmentId")] Employee employee)
- {
- if (ModelState.IsValid)
- {
- db.Employees.Add(employee);
- db.SaveChanges();
- return RedirectToAction("Index");
- }
-
- ViewBag.DepartmentId = new SelectList(db.Departments, "DeptId", "DepartmentName", employee.DepartmentId);
- return View(employee);
- }
-
- [Authorize(Roles = "Admin,Employee")]
- public ActionResult Edit(int? id)
- {
- if (id == null)
- {
- return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
- }
- Employee employee = db.Employees.Find(id);
- if (employee == null)
- {
- return HttpNotFound();
- }
- ViewBag.DepartmentId = new SelectList(db.Departments, "DeptId", "DepartmentName", employee.DepartmentId);
- return View(employee);
- }
-
- [Authorize(Roles = "Admin,Employee")]
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Edit([Bind(Include = "EmpId,Name,Gender,Age,Position,Office,HireDate,Salary,DepartmentId")] Employee employee)
- {
- if (ModelState.IsValid)
- {
- db.Entry(employee).State = EntityState.Modified;
- db.SaveChanges();
- return RedirectToAction("Index");
- }
- 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.Find(id);
- if (employee == null)
- {
- return HttpNotFound();
- }
- return 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.Dispose(disposing);
- }
- }
- }
Similarly “Add” two more controller
- Home Controller
- Account Controller
Step 6
Right-click on Controllers folder add Home controller first.
A window will appear. Choose MVC5 Controller-Empty and click "Add".
After clicking on "Add", another window will appear with DefaultController. Change the name to HomeController and click "Add". The HomeController will be added under the Controllers folder. Don’t change the Controller suffix for all controllers, change only the highlight, and instead of Default, just change Home.
- using MvcCustomAuthenticationFilter_Demo.Models;
- using System.Web.Mvc;
-
- namespace MvcCustomAuthenticationFilter_Demo.Controllers
- {
- public class HomeController : Controller
- {
- [CustomAuthenticationFilter]
- public ActionResult Index()
- {
- return View();
- }
-
- public ActionResult About()
- {
- return View();
- }
-
- [CustomAuthenticationFilter]
- public ActionResult Contact()
- {
- return View();
- }
- }
- }
Similarly add another controller AccountController.
- using MvcCustomAuthenticationFilter_Demo.Models;
- using System.Web.Mvc;
-
- namespace MvcCustomAuthenticationFilter_Demo.Controllers
- {
- public class AccountController : Controller
- {
-
- public ActionResult Login()
- {
- return View();
- }
-
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Login(UserLogin login)
- {
- if (ModelState.IsValid)
- {
- if (login.Username.ToLower()=="admin" && login.Password=="admin")
- {
- Session["Username"] = login.Username;
- return RedirectToAction("Index", "Home");
- }
- else
- {
- ModelState.AddModelError("", "Invalid User Name or Password");
- return View(login);
- }
-
- }
- return View(login);
- }
- }
- }
Step 7
Right-click on Models folder and create a UserRoleProvider class.
UserRoleProvider Class
- using System;
- using System.Linq;
- using System.Web.Security;
-
- namespace MvcRoleBasedAuthentication_Demo.Models
- {
- public class UserRoleProvider : RoleProvider
- {
- public override string ApplicationName
- {
- get
- {
- throw new NotImplementedException();
- }
-
- set
- {
- throw new NotImplementedException();
- }
- }
-
- public override void AddUsersToRoles(string[] usernames, string[] roleNames)
- {
- throw new NotImplementedException();
- }
-
- public override void CreateRole(string roleName)
- {
- throw new NotImplementedException();
- }
-
- public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
- {
- throw new NotImplementedException();
- }
-
- public override string[] FindUsersInRole(string roleName, string usernameToMatch)
- {
- throw new NotImplementedException();
- }
-
- public override string[] GetAllRoles()
- {
- throw new NotImplementedException();
- }
-
- public override string[] GetRolesForUser(string username)
- {
- using (EmployeeContext _Context=new EmployeeContext())
- {
- var userRoles = (from user in _Context.Users
- join roleMapping in _Context.UserRoleMappings
- on user.Id equals roleMapping.UserId
- join role in _Context.Roles
- on roleMapping.RoleId equals role.Id
- where user.Username == username
- select role.RoleName).ToArray();
- return 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(string roleName)
- {
- throw new NotImplementedException();
- }
- }
- }
Step 8
Create CustomAuthenticationFilter class and implement ActionFilterAttribute and IAuthenticationFilter interface methods.
- using System;
- using System.Web.Mvc;
- using System.Web.Mvc.Filters;
- using System.Web.Routing;
-
- namespace MvcCustomAuthenticationFilter_Demo.Models
- {
- public class CustomAuthenticationFilter : ActionFilterAttribute, IAuthenticationFilter
- {
- void IAuthenticationFilter.OnAuthentication(AuthenticationContext filterContext)
- {
- if (string.IsNullOrEmpty(Convert.ToString(filterContext.HttpContext.Session["Username"])))
- {
- filterContext.Result = new HttpUnauthorizedResult();
- }
- }
-
- void IAuthenticationFilter.OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
- {
- if (filterContext.Result == null || filterContext.Result is HttpUnauthorizedResult)
- {
- filterContext.Result = new RedirectToRouteResult(
- new RouteValueDictionary {
- { "controller", "Account" },
- { "action", "Login" } });
- }
- }
- }
- }
Step 9
Open web config file and write following code.
- <authentication mode="Forms">
- <forms loginUrl="Account/Login"></forms>
- </authentication>
- <roleManager defaultProvider="userRoleProvider" enabled="true">
- <providers>
- <clear/>
- <add name="userRoleProvider" type="MvcRoleBasedAuthentication_Demo.Models.UserRoleProvider"/>
- </providers>
- </roleManager>
Step 10
Right-click on the Login action method in Account Controller and create Login View.
- @model MvcCustomAuthenticationFilter_Demo.Models.UserLogin
-
- @{
- ViewBag.Title = "Login";
- }
-
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
- <div class="panel custom-panel">
- <div class="panel-heading">
- <h3>Log in</h3>
- </div>
- <div class="panel-body">
- <div class="form-group">
- @Html.LabelFor(m => m.Username)
- @Html.TextBoxFor(m => m.Username, new { @class = "form-control" })
- @Html.ValidationMessageFor(m => m.Username)
- </div>
- <div class="form-group">
- @Html.LabelFor(m => m.Password)
- @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
- @Html.ValidationMessageFor(m => m.Password)
- </div>
- <div class="form-group">
- <button type="submit" class="btn btn-primary">Login</button>
- </div>
- </div>
- </div>
- }
Now, run the application and you will see that when you want to access the Index and Contact page, it will navigate to the Login page of Account Controller. But you can access the “About” page as I have not applied custom authentication filter on this action method. Now login with the proper credentials and once you log in, you can access each page of the application.