Site icon Tutexchange

AsyncAuthorization filter in ASP.NET CORE MVC

Advertisements

AsyncAuthorization filter in ASP.NET CORE MVC

AsyncAuthorization filter is an async version of Authorization filter.

Let’s create a Custom AsyncAuthorizationFilter with the name ‘CustomAsyncAuthorizationFilter‘ and we are going to inherit with IAsyncAuthorizationFilter interface and implement OnAuthorizationAsync method in this method we are going to read UserId from the session and get the role of User using UserId from the database.  Then we are going to check if the role of the user is an admin or not if not then we are going to redirect it to an error page.

Code Snippet of CustomAsyncAuthorizationFilter

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Routing;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;
using WebApplication4.Models;

namespace WebApplication4.Filters
{
    public class CustomAsyncAuthorizationFilter : Attribute, IAsyncAuthorizationFilter
    {
        public readonly DatabaseContext _dbcontext;
        public CustomAsyncAuthorizationFilter(DatabaseContext dbcontext)
        {
            _dbcontext = dbcontext;
        }

        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            int? currentUserId = context.HttpContext.Session.GetInt32("UserId");

            var getroleName = await (from userrole in _dbcontext.UserRoles
                                     where userrole.UserId == currentUserId
                                     select userrole.Name).SingleOrDefaultAsync();


            // Use 'await' to get data from the database 

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

How to Apply Filter on Controller

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

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

Exit mobile version