Add Authorize Policy Dynamically to all Controllers in Asp.Net Core 3.1

How to add Authorize Policy dynamically for all the Controllers in Asp.Net Core 3.1 Application

November 24, 2020

In this article we will cover how to add Authorize Policy dynamically for all the Controllers in Asp.Net Core 3.1 Application

AuthorizeController.cs

Create AuthorizeController Class as mentioned below. (This class will Apply Authorize Policy to all the Controllers.)

using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.Authorization;
using System.Collections.Generic;
using System.Linq;
 
namespace HpBlogs
{
    public class AuthorizeController : IControllerModelConvention
    {
        public void Apply(ControllerModel controller)
        {
            // ADD Controllers in list if do not have to add policy
            List<stringControllers_List_To_Exclude = new List<string>()
            {
                "Home","Login"
            };
 
            if (!Controllers_List_To_Exclude.Any(a => a.Equals(controller.ControllerName)))
            {
                // Apply Policy based on Controller OR Apply Common Policy to all.
 
                if (controller.ControllerName.ToLower().Contains("admin"))
                    controller.Filters.Add(new AuthorizeFilter("AdminPolicy"));
                else
                    controller.Filters.Add(new AuthorizeFilter("CommonPolicy"));
            }
        }
    }
}

Startup.cs

Register AuthorizeController inside the ConfigureServices method as mentioned below

services.AddControllers(o =>
{
    o.Conventions.Add(new AuthorizeController());
});
 
services.AddAuthorization(o =>
{
    o.AddPolicy("AdminPolicy"b =>
    {
        b.RequireAuthenticatedUser();  // Write Policy Logic as per requiremnent
    });
 
    o.AddPolicy("CommonPolicy"b =>
    {
        b.RequireAuthenticatedUser(); // Write Policy Logic as per requiremnent
    });
});

Post Comments(0)

Leave a reply

Will not be displayed in comment box .

Loading...