How to dynamically add roles to authorize attribute for controller in c#?

12 Points
1 Posts

I want to be able to create an Authorize attribute to my controller class that I can add roles to from a database, so that I don't have to 'set' the roles during development or compile time, as in [Authorize(Roles="Role1, Role2")] etc.

So, I want something like [Authorize(Roles = GetListOfRoles()]

Views: 420
Total Answered: 1
Total Marked As Answer: 0
Posted On: 19-Apr-2024 00:35

Share:   fb twitter linkedin
120 Points
9 Posts

To dynamically add roles to authorized controllers in C#, you typically need to implement a custom authorization filter.

Here's a step-by-step guide on how to achieve this:

  1. Create a Custom Authorization Filter: First, create a class that implements the IAuthorizationFilter interface. This interface has a method OnAuthorization that gets called before an action method is invoked.
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Filters;

    public class DynamicRolesAuthorizationFilter : IAuthorizationFilter
        public void OnAuthorization(AuthorizationFilterContext context)
            // Your logic to dynamically add roles
            var roles = GetDynamicRoles();

            var policy = new AuthorizationPolicyBuilder()

            var authService = context.HttpContext.RequestServices.GetService(typeof(IAuthorizationService)) as IAuthorizationService;
            var authResult = authService.AuthorizeAsync(context.HttpContext.User, null, policy).GetAwaiter().GetResult();

            if (!authResult.Succeeded)
                context.Result = new ForbidResult();

        private string[] GetDynamicRoles()
            // Your logic to fetch roles dynamically
            return new string[] { "Admin", "Manager" };
  2. Apply the Filter to Controllers or Actions: Now, you can apply this filter to your controllers or actions where you want to dynamically add roles.
    public class YourController : Controller
        // Controller actions
  3. Register the Filter: Finally, make sure you register your custom filter in the ASP.NET Core application's Startup class.
    public void ConfigureServices(IServiceCollection services)
        // Other configurations...

        services.AddControllersWithViews(options =>



With this setup, every time a request comes to a controller or action decorated with the [Authorize] attribute, the DynamicRolesAuthorizationFilter will be triggered. Inside this filter, you can implement your logic to dynamically determine the roles that are authorized to access the resource.


Posted On: 19-Apr-2024 23:50
 Log In to Chat