No doubt what it requires is to create a FilterAttribute
, where by means of a notation the controller is invoked just before so that it can validate if the session is valid. This example uses Owin authentication but you can use it with any other type of authentication:
public class ValidateAuthenticationFilterAttribute : ActionFilterAttribute
{
IAuthenticationManager Authentication
{
get { return System.Web.HttpContext.Current.GetOwinContext().Authentication; }
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!Authentication.User.Identity.IsAuthenticated)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Login", action = "Index" }));
}
base.OnActionExecuting(filterContext);
}
}
Where only to put it to work is invoked in the following way:
[ValidateAuthenticationFilter]
public class TestController : Controller
{
//To Do
}
The previous code works well, however, as a best practice I recommend that you create a global controller so that you only put the reference to FilterAtribute
once, without the need to write the filter notation every time you sign up a controller. For example:
Filter attribute code:
public class ValidateAuthenticationFilterAttribute : ActionFilterAttribute
{
//Lógica para validar la sesión
}
Global controller code:
[ValidateAuthenticationFilter]
public class GlobalController : Controller
{
//Acciones genéricas para todos los controladores
}
Code of any driver that you sign up for in your project:
public class TestController : GlobalController
{
//Acciones y lógica de cualquier controlador
}
In this way, when inheriting from the global controller, the session would be validated automatically. For the answer to be more complete according to your needs, it would be good to edit your question putting the type of authentication you use in your application and to be able to adjust the code.