In ASP.NET Core MVC, Authorization Filters are used to determine whether a user is authorized to access a specific resource. These filters are executed before any other filters, including action, result, or exception filters.

Authorization filters are particularly useful when you want to implement custom logic for access control based on roles, claims, or session values.

In this article, we will:

  • Create a custom authorization filter named CustomAuthorizationFilterAttribute
  • Inherit from the IAuthorizationFilter interface
  • Implement the OnAuthorization method
  • Check the session for a UserRole value
  • Redirect the user to an error page if they are not authorized

Code Snippet of CustomAuthorizationFilterAttribute

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Routing;
using System;

namespace WebApplication4.Filters
{
    public class CustomAuthorizationFilterAttribute : Attribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            string currentUserRole = Convert.ToString(context.HttpContext.Session.GetString("UserRole"));

            if (!string.IsNullOrEmpty(currentUserRole))
            {
                if (currentUserRole != "Admin")
                {
                    context.Result = new RedirectToRouteResult
                (
                new RouteValueDictionary(new
                {
                    action = "Error",
                    controller = "Error"
                }));

                }
                else
                {
                    context.Result = new RedirectToRouteResult
               (
               new RouteValueDictionary(new
               {
                   action = "Error",
                   controller = "Error"
               }));

                }
            }
            else
            {
                context.Result = new RedirectToRouteResult
                (
                new RouteValueDictionary(new
                {
                    action = "Error",
                    controller = "Error"
                }));

            }
        }
    }
}

How to Apply Filter on Controller

using System;
using Microsoft.AspNetCore.Mvc;
using WebApplication4.Filters;

namespace WebApplication4.Controllers
{
    [TypeFilter(typeof(CustomAuthorizationFilterAttribute))]
    public class DefaultController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

Conclusion

Authorization filters in ASP.NET Core MVC are powerful tools for implementing custom access control logic. By using a session-based approach, you can easily restrict access based on roles or other custom criteria.

In this example, we built a custom filter that checks if the UserRole session variable is set to “Admin”. If not, the user is redirected to an error page.

Let me know if you’d like this article in PDF format or want to extend the example with role-based claims or policy-based authorization.

By Saineshwar

Microsoft MVP for Developer Technologies | C# Corner MVP | Code project MVP | Senior Technical Lead | Author | Speaker | Love .Net | Full Stack developer | Open source contributor.