2023
Authenticating User Login using custom filter in Asp.Net MVC
85
Customer Filter Attribute
Attribute filters refers to specific piece of codes which will execute whenever the action will be called on which they are applied. We can create common custom filters and use them for authentication. You have to follow these steps :-
First of all add one new class file and name it CustomFilter.cs and copy the code from below
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace CustomFilter.Models { public class AuthenticateUser : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { base.OnActionExecuting(context); if (!IsValidLogin()) { context.Result = new RedirectToRouteResult( new RouteValueDictionary { {"controller", "Users"}, {"action", "Login"} }); } } public bool IsValidLogin() { if ("Value from cookie"!= "0") { return true; } //Add code for User authentication fail here return false; } } }
Now reference this class in your controller and apply this attribute on action or controller level like you can see below
You can copy the code from below. You can implement your own logic for validating if user is logged in or not in IsValidLogin method in custom filter class.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using CustomFilter.Models; namespace CustomFilter.Controllers { [AuthenticateUser] //Use this line to apply authentication on action level public class HomeController : Controller { // [AuthenticateUser] //Use this line to apply authentication on action level public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
Now, whenever you will call any action having this filter attribute, it will first go to custom filter and validate the user login. So this is how we can implement Authenticating User Login using custom filter in Asp.Net MVC.