Site icon Tutexchange

Authorization filter in ASP.NET CORE MVC

Advertisements

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:

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.

Exit mobile version