DynamicAuthorization.Mvc.Core 1.2.1

There is a newer version of this package available.
See the version list below for details.
dotnet add package DynamicAuthorization.Mvc.Core --version 1.2.1                
NuGet\Install-Package DynamicAuthorization.Mvc.Core -Version 1.2.1                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="DynamicAuthorization.Mvc.Core" Version="1.2.1" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add DynamicAuthorization.Mvc.Core --version 1.2.1                
#r "nuget: DynamicAuthorization.Mvc.Core, 1.2.1"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install DynamicAuthorization.Mvc.Core as a Cake Addin
#addin nuget:?package=DynamicAuthorization.Mvc.Core&version=1.2.1

// Install DynamicAuthorization.Mvc.Core as a Cake Tool
#tool nuget:?package=DynamicAuthorization.Mvc.Core&version=1.2.1                

Dynamic Role-Based Authorization in ASP.NET Core MVC 2.1, 3.1, 5.0 and 6.0 NuGet

You already know how role-based authorization works in ASP.NET Core.

[Authorize(Roles = "Administrator")]
public class AdministrationController : Controller
{
}

But what if you don't want hardcode roles on the Authorize attribute or create roles later and specify in which controller and action it has access without touching source code?

DynamicAuthorization helps you authorize users without hardcoding role(s) on the Authorize attribute with minimum effort. DynamicAuthorization is built at the top of ASP.NET Core Identity and uses identity mechanism for managing roles and authorizing users.

Install the DynamicAuthorization.Mvc.Core NuGet package

Install-Package DynamicAuthorization.Mvc.Core

or

dotnet add package DynamicAuthorization.Mvc.Core

Then, add AddDynamicAuthorization() to IServiceCollection in Startup.ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services
        .AddIdentity<IdentityUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = false)
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();
        
    services
        .AddDynamicAuthorization<ApplicationDbContext>(options => options.DefaultAdminUser = "UserName")

You can set the default admin username via DefaultAdminUser config to access everywhere without creating a default admin role and its access.

Then install JSON or SQLSever store to save role access.

To install DynamicAuthorization.Mvc.JsonStore NuGet package

Install-Package DynamicAuthorization.Mvc.JsonStore

or

dotnet add package DynamicAuthorization.Mvc.JsonStore
public void ConfigureServices(IServiceCollection services)
{
        
    services
        .AddDynamicAuthorization<ApplicationDbContext>(options => options.DefaultAdminUser = "UserName")
        .AddJsonStore(options => options.FilePath = "FilePath");

Role access will be saved in a JSON file and you can specify the file path FilePath config.

Or install SQLServer store DynamicAuthorization.Mvc.MsSqlServerStore NuGet package

Install-Package DynamicAuthorization.Mvc.MsSqlServerStore

or

dotnet add package DynamicAuthorization.Mvc.MsSqlServerStore
public void ConfigureServices(IServiceCollection services)
{
        
    services
        .AddDynamicAuthorization<ApplicationDbContext>(options => options.DefaultAdminUser = "UserName")
        .AddSqlServerStore(options => options.ConnectionString = "ConnectionString");

You can decorate controllers and actions with DisplayName attribute to show the user a more meaningful name instead of controller and action name.

[DisplayName("Access Management")]
public class AccessController : Controller
{

    // GET: Access
    [DisplayName("Access List")]
    public async Task<ActionResult> Index()
}

You can also the default UI for managing roles and assigning roles to users if you don't want to implement them by yourself.

Install the DynamicAuthorization.Mvc.Ui NuGet package

Install-Package DynamicAuthorization.Mvc.Ui

Then AddUi to DynamicAuthorization registration:

services
        .AddDynamicAuthorization<ApplicationDbContext>(options => options.DefaultAdminUser = "UserName")
        .AddJsonStore(options => options.FilePath = "FilePath")
        .AddUi();

Use http://<your-app>/role url to manage roles and assign access to a role.

create project

Use http://<your-app>/userrole url to assign roles to users.

You can also use a custom TageHelper to check whether the user has access to view content or not. create a custom tag helper that inherits from SecureContentTagHelper

[HtmlTargetElement("secure-content")]
public class MySecureContentTagHelper : SecureContentTagHelper<ApplicationDbContext>
{
    public MySecureContentTagHelper(
        ApplicationDbContext dbContext,
        DynamicAuthorizationOptions authorizationOptions,
        IRoleAccessStore roleAccessStore
        )
        : base(dbContext, authorizationOptions, roleAccessStore)
    {
    }
}

In each view wrap a content or an anchor tag inside secure-content tag:

<ul class="nav navbar-nav">
    <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
    <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
    <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
    
    <secure-content asp-area="" asp-controller="Role" asp-action="Index">
        <li><a asp-area="" asp-controller="Role" asp-action="Index">Role</a></li>
    </secure-content>
    <secure-content asp-area="" asp-controller="Access" asp-action="Index">
        <li><a asp-area="" asp-controller="Access" asp-action="Index">Access</a></li>
    </secure-content>
</ul>

Don't forget to add your tag halper namespace to _ViewImports.cshtml:

@using SampleMvcWebApp
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, SampleMvcWebApp

If you extended IdentityUser or you changed user and role key, you should pass user and role type too. for example:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { ... }
public class MySecureContentTagHelper : SecureContentTagHelper<ApplicationDbContext, ApplicationUser> { ... }

or

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, int> { ... }
public class MySecureContentTagHelper : SecureContentTagHelper<ApplicationDbContext, ApplicationUser, ApplicationRole, int> { ... }

If you don't want to use the default UI, follow the below steps to discover controllers and actions and give access to the role and then assign role(s) to the user. The next step is discovering controllers and actions. IMvcControllerDiscovery return all controllers and actions that decorated with [Authorize] attribute. IMvcControllerDiscovery.GetControllers() method returns list of MvcControllerInfo:

public class MvcControllerInfo
{
    public string Id => $"{AreaName}:{Name}";

    public string Name { get; set; }

    public string DisplayName { get; set; }

    public string AreaName { get; set; }

    public IEnumerable<MvcActionInfo> Actions { get; set; }
}

public class MvcActionInfo
{
    public string Id => $"{ControllerId}:{Name}";

    public string Name { get; set; }

    public string DisplayName { get; set; }

    public string ControllerId { get; set; }
}

The next step is creating a role to assign access to it. Use RoleManager<> to create role and IRoleAccessStore to store role access.

var role = new IdentityRole { Name = "RoleName" };
var result = await _roleManager.CreateAsync(role);

var controllers = _mvcControllerDiscovery.GetControllers();
var roleAccess = new RoleAccess
{
    Controllers = controllers.First(),
    RoleId = role.Id
};
await _roleAccessStore.AddRoleAccessAsync(roleAccess);

The final step is assigning a created role to a user:

var user = await _userManager.FindByIdAsync("someId");
await _userManager.AddToRolesAsync(user, new [] { "RoleName" });

And now the user only can access those controllers and actions that his roles can access.

Here is an example to create a role and assign access to the role.

public class RoleViewModel
{
    [Required]
    [StringLength(256, ErrorMessage = "The {0} must be at least {2} characters long.")]
    public string Name { get; set; }

    public IEnumerable<MvcControllerInfo> SelectedControllers { get; set; }
}

[DisplayName("Role Management")]
public class RoleController : Controller
{
    private readonly IMvcControllerDiscovery _mvcControllerDiscovery;
    private readonly IRoleAccessStore _roleAccessStore;
    private readonly RoleManager<IdentityRole> _roleManager;

    public RoleController(
        IMvcControllerDiscovery mvcControllerDiscovery,
        IRoleAccessStore roleAccessStore,
        RoleManager<IdentityRole> roleManager
        )
    {
        _mvcControllerDiscovery = mvcControllerDiscovery;
        _roleManager = roleManager;
        _roleAccessStore = roleAccessStore;
    }

    // GET: Role/Create
    [DisplayName("Create Role")]
    public ActionResult Create()
    {
        var controllers = _mvcControllerDiscovery.GetControllers();
        ViewData["Controllers"] = controllers;

        return View();
    }
    
    // POST: Role/Create
    [HttpPost, ValidateAntiForgeryToken]
    public async Task<ActionResult> Create(RoleViewModel viewModel)
    {
        if (!ModelState.IsValid)
        {
            ViewData["Controllers"] = _mvcControllerDiscovery.GetControllers();
            return View(viewModel);
        }

        var role = new IdentityRole { Name = viewModel.Name };
        var result = await _roleManager.CreateAsync(role);

        if (!result.Succeeded)
        {
            foreach (var error in result.Errors)
                ModelState.AddModelError("", error.Description);

            ViewData["Controllers"] = _mvcControllerDiscovery.GetControllers();
            return View(viewModel);
        }

        if (viewModel.SelectedControllers != null && viewModel.SelectedControllers.Any())
        {
            foreach (var controller in viewModel.SelectedControllers)
                foreach (var action in controller.Actions)
                    action.ControllerId = controller.Id;

            var roleAccess = new RoleAccess
            {
                Controllers = viewModel.SelectedControllers.ToList(),
                RoleId = role.Id
            };
            await _roleAccessStore.AddRoleAccessAsync(roleAccess);
        }

        return RedirectToAction(nameof(Index));
    }
}

Checkout samples to view full implementation.

To implement DynamicAuthorization step by step by yourself checkout manual branch.

Product Compatible and additional computed target framework versions.
.NET net5.0 is compatible.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 is compatible. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (3)

Showing the top 3 NuGet packages that depend on DynamicAuthorization.Mvc.Core:

Package Downloads
DynamicAuthorization.Mvc.MsSqlServerStore

SQL Sever store for DynamicAuthorization

DynamicAuthorization.Mvc.Ui

Simple web UI to create role and role access for DynamicAuthorization

DynamicAuthorization.Mvc.JsonStore

JSON store for DynamicAuthorization

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.2.2 2,846 4/4/2023
1.2.1 1,861 1/16/2022
1.2.0 4,110 3/23/2021
1.1.1 1,798 3/19/2021
1.1.0 1,690 3/16/2021
1.0.3 1,281 1/23/2021
1.0.2 1,602 11/17/2020
1.0.1 1,244 11/3/2020
1.0.0 1,698 4/28/2020