ASP.NET MVC: Implement Custom Authorization Filters with Session

Updated on     Kisan Patel

Filters are features that allows us to execute logic at different stages through out the controller pipeline. we can apply filters in two ways, using attributes at the controller level as well as the action methods.

There are four different types of filters. each of these filters are implemented using interface.

  1. Authorization that implements IAuthorizationFilter
  2. Action that implements IActionFilter
  3. Result that implements IResultFilter
  4. Exception that implements IExceptionFilter

In this tutorial we have learn how to implement custom login functionality using session with Authorization filters.

First, create Filters folder inside your ASP.NET MVC projects. Now all your filters class created inside Filters folder. Now, create MyAuthorizationAttribute class that inherit FilterAttribute class. You also need to inherit IAuthorizationFilter class and implement OnAuthorization method as shown in below code.

IAuthorizationFilter-example

In this tutorial, we have used Session variable loggedin and set it to true when user is logged in and also implement Logout action that Abandon Session as shown in below code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcAuthorizeDemo.Filters;

namespace MvcAuthorizeDemo.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Account/

        public ActionResult Index()
        {
            return View();
        }


        public ActionResult Login()
        {
            Session["loggedin"] = true;
            return View();
        }

        public ActionResult Logout()
        {
            Session.Abandon();
            return View();
        }

        [MyAuthorization]
        public ActionResult Protected()
        {
            return View();
        }

    }
}

You can also see, we have also add MyAuthorization attribute to the Protected action method.

Lets implement OnAuthorization method in MyAthorizationAttribute class. In OnAuthorization method first we have get the information about session and store into isLoggedIn boolean variable then check if isLoggedIn variable is true or false in if condition.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcAuthorizeDemo.Filters
{
    public class MyAuthorizationAttribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var session = filterContext.HttpContext.Session;
            var isLoggedIn = Convert.ToBoolean(session["loggedin"]);
            if (!isLoggedIn)
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
    }
}

We can also add MyAuthorization attribute to the AccountController. This will protect the entire controller.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcAuthorizeDemo.Filters;

namespace MvcAuthorizeDemo.Controllers
{
    [MyAuthorization]
    public class AccountController : Controller
    {
        //
        // GET: /Account/

        [AllowAnonymous]
        public ActionResult Index()
        {
            return View();
        }

        [AllowAnonymous]
        public ActionResult Login()
        {
            Session["loggedin"] = true;
            return View();
        }

        public ActionResult Logout()
        {
            Session.Abandon();
            return View();
        }
        
        public ActionResult Protected()
        {
            return View();
        }

    }
}

If you don’t want to protect Login action method then you need to implement AllowAnonymous attribute as shown in below code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcAuthorizeDemo.Filters
{
    public class MyAuthorizationAttribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var session = filterContext.HttpContext.Session;
            var isLoggedIn = Convert.ToBoolean(session["loggedin"]);
            if (!isLoggedIn)
            {
                var action = filterContext.ActionDescriptor;

                if (!action.IsDefined(typeof(AllowAnonymousAttribute), true))
                {
                    filterContext.Result = new HttpUnauthorizedResult();
                }
            }
        }
    }
}

Here, We can get the information about action methods using ActionDescriptor object and check AllowAnonymousAttribute is defined using IsDefined method.

It’s Done!


ASP.NET MVC

Leave a Reply