Giter Site home page Giter Site logo

mo-esmp / dynamicrolebasedauthorizationnetcore Goto Github PK

View Code? Open in Web Editor NEW
434.0 434.0 92.0 2.69 MB

Dynamic Role-Based Access Control for ASP.NET Core MVC and Web API

License: GNU General Public License v3.0

C# 71.70% HTML 11.99% CSS 1.87% JavaScript 14.45%
asp-net-core asp-net-core-identity asp-net-identity discovering-controllers dynamic-auth dynamic-rbac hardcode-roles identity rbac rbac-authorization rbac-roles role-based-access-control

dynamicrolebasedauthorizationnetcore's People

Contributors

antoniocampos avatar dependabot[bot] avatar kajoosh avatar mo-esmp avatar phoenixatom avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dynamicrolebasedauthorizationnetcore's Issues

[Idea] new feature

Hello,
I would like to suggest one new feature here.
Imaging big applications which has mother company with child companies, all of them has HR, but with different access.
HR from Mother company can create all users for all other child companies and assign them all roles.
But HR from Child company can create only users for their company and only assign some specific roles, example(Warehouse, master data ...)
Maybe to implement some feature where based on role if user can create new user to distinguish which roles can assign to this user.
What do you think, do you see any benefit of that ?

Regards,
Danijel

AddUI requires IMvcBuilder

Good day. Im working on an asp.net core 3.1 application that uses identity for authentication.
When i try to implement the addUI method though it's complaining that the addui needs a imvcbuilder.

i may just be missing something but where do i find this?

Cant Get Requested Url in .Net Core 3.1

hello please update DynamicRoleBasedAuthorizationNETCore project to .net core 3.1
thanks, a lot
when i call authorize controller for example /roles/index
in filter the url is /account/login not show my main path.

because we use app.authorizaiton & serivce.useControllersAndView & app.EndPoint in .net Core 3.1

پیاده سازی کلاس MySecureContentTagHelper در حالت کلاس کاستوم

سلام
من همه کلاس های identityt و مطابق داکیومنت مایکروسافت سفارشی کردم
ApplicationRole
ApplicationRoleClaim
ApplicationUser
ApplicationUserClaim
ApplicationUserLogin
ApplicationUserRole
ApplicationUserToken
در پیاده سازی کلاس تگ هلپر مطابق زیر خطا داره
[HtmlTargetElement("secure-content")] public class MySecureContentTagHelper : SecureContentTagHelper<ApplicationDbContext, ApplicationUser, ApplicationRole, int> { public MySecureContentTagHelper( ApplicationDbContext dbContext, DynamicAuthorizationOptions authorizationOptions, IRoleAccessStore roleAccessStore) : base(dbContext, authorizationOptions, roleAccessStore) { } }

Get List<Menu> based on user role or claim

Hello, thanks for this, its very creative approach and unique, is it possible to build a menu hierarchy based on the users roles/claims at startup/cached, could you please show us so I can tie the Mo-esmpMenuHelper into a _SideBarLayout

I can help with adding the BS 5 styles with a PR if you want.

How to include Razor Pages & Page Handlers

Excellent project!

How would I go about handling RazorPages as well as/instead of controllers?

Particularly how to implement MvcControllerDiscovery for Razor Pages & Page Handlers where

  • MvcRazorPageInfo would be equivalent of MvcControllerInfo
  • MvcRazorPageHandlerInfo would be equivalent of MvcActionInfo

Role Based Menu

Hello, can we generate a Role Based Menu option when we configure services.

Also I think we can use this in our template for breacrumbs
This template is much more easier to use than the dotnet boxed or rehans template.

Do you have any suggestions to customizing T4 tempaltes to do scaffolding from table controller and views

thanks

accessList is always returning null

Hi, been stuck in this problem and i can't figure it out why i'm getting the accessList null... I can create and edit the role, but no items in accesslist.

Here's my startup:


  services.AddDbContext<LoginContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("Default"));
            });
            services.AddIdentity<User, IdentityRole>(options =>
            {
                options.Password.RequiredLength = 3;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = false;
                options.Password.RequireLowercase = false;
                options.Password.RequireDigit = false;
                options.User.RequireUniqueEmail = true;
            }).AddEntityFrameworkStores<LoginContext>()
              .AddErrorDescriber<TranslatedIdentityErrorDescriber>();

            services
                .AddDynamicAuthorization<LoginContext>(options => options.DefaultAdminUser = "admin")
                .AddSqlServerStore(options => options.ConnectionString = "Default"); 

            services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath = "/Login";
            });

            services.AddScoped<IUserClaimsPrincipalFactory<User>, CustomUserClaimsPrincipalFactory>();

Here's my DbContext class, i think it might be here the problem, but i don't know what else to try:

   public class LoginContext : IdentityDbContext
    {
        public LoginContext(DbContextOptions<LoginContext> options) : base(options)
        {
            //irá criar o banco e a estrutura de tabelas necessárias
            this.Database.EnsureCreated();
        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            builder.ApplyConfiguration<User>(new UserConfiguration());
            builder.ApplyConfiguration<Role>(new RoleConfiguration());
        }
    }   
    public class RoleConfiguration : IEntityTypeConfiguration<Role>
    {
        public void Configure(EntityTypeBuilder<Role> builder)
        {
       
        }
    }

When debbuging, both lines seens successfull, the objects are loaded correctly:

await _roleAccessStore.AddRoleAccessAsync(roleAccess);
 await _roleAccessStore.EditRoleAccessAsync(roleAccess);

Here, the return is always null:

var accessList = await _roleAccessStore.GetRoleAccessAsync(role.Id);

Any idea what could be wrong here please? Thanks

Question: DynamicAuthorization.Mvc.Ui

Is it possible to scaffold the views of the DynamicAuthorization.Mvc.Ui? I have a theme I am applying to the application, and I want the roles pages to be similarly templated.

Thank you

Net 6 , Edit User Rol

Hello.
I am editing a user who is an administrator and I am providing him with the "Role Management" role that is in the "AspNetRoles" table with the values "Role Management". The user is an administrator and it gives me the following error.

InvalidOperationException: Role ROLE MANAGEMENT does not exist. Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore<TUser, TRole, TContext, TKey, TUserClaim, TUserRole, TUserLogin, TUserToken, TRoleClaim>.AddToRoleAsync(TUser user, string normalizedRoleName, CancellationToken cancellationToken)

InvalidOperationException: Role ROLE MANAGEMENT does not exist. Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore<TUser, TRole, TContext, TKey, TUserClaim, TUserRole, TUserLogin, TUserToken, TRoleClaim>.AddToRoleAsync(TUser user, string normalizedRoleName, CancellationToken cancellationToken) Microsoft.AspNetCore.Identity.UserManager<TUser>.AddToRolesAsync(TUser user, IEnumerable<string> roles) DynamicAuthorization.Mvc.Ui.Controllers.UserRoleController<TRole, TUser, TKey>.Edit(UserRoleViewModel viewModel) in UserRoleController.cs + await _userManager.AddToRolesAsync(user, viewModel.Roles); lambda_method285(Closure , object ) Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor+TaskOfActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments) System.Threading.Tasks.ValueTask<TResult>.get_Result() System.Runtime.CompilerServices.ValueTaskAwaiter<TResult>.GetResult() Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask<IActionResult> actionResultValueTask) Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult) Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Fix null Actions when creating Role

In Role>Create view this code need to be fixed. it's causing null Actions in Post Edit
From

 @if (controller.Actions.Any())
                                {
                                    <ol>
                                        @foreach (var action in controller.Actions)
                                        {
                                            name = action.DisplayName ?? action.Name;
                                            <li data-value="@action.Name">@name</li>
                                        }
                                    </ol>
                                }

To

 @if (controller.Actions.Any())
                                {
                                    <ul>
                                        @foreach (var action in controller.Actions)
                                        {
                                            name = action.DisplayName ?? action.Name;
                                            <li data-value="@action.Name">@name</li>
                                        }
                                    </ul>
                                }

Pulll: Adding Claims to Role - to create a sub group

Hello, I am trying add role-claims to your code, can you please pull this and help me if its correct.

Use Case: we need create groups for data access inside a role. And, right now I have role for manager but I want limit the managers data access to sallies, budgets etc. based on their area like state or city or region.

So EastCoast-Managers, WestCoast-Managers etc. can only see salaries in their areas. I am trying the code below, but I don't know how to create those groups like in Active Directory

public async Task<ActionResult> UpdateRole(string id, string name, List<KeyValuePair<string, string>> claims)
        {
            try
            {
                var role = await _roleManager.FindByIdAsync(id);
                if (role == null)
                    return NotFound("mo esmp for Role not found.");

                role.Name = name;

                var result = await _roleManager.UpdateAsync(role);
                if (result.Succeeded)
                {
                    _logger.LogInformation("Updated role {name}.", role.Name);

                    var roleClaims = await _roleManager.GetClaimsAsync(role);

                    foreach (var kvp in claims.Where(a => !roleClaims.Any(b => _claimTypes[a.Key] == b.Type && a.Value == b.Value)))
                        await _roleManager.AddClaimAsync(role, new Claim(_claimTypes[kvp.Key], kvp.Value));

                    foreach (var claim in roleClaims.Where(a => !claims.Any(b => a.Type == _claimTypes[b.Key] && a.Value == b.Value)))
                        await _roleManager.RemoveClaimAsync(role, claim);

                    return NoContent();
                }
                else
                    return BadRequest(result.Errors.First().Description);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failure updating role {roleId}.", id);
                return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
            }
        }

خطا در استفاده از پروژه در MVC Core 5.0

با سلام
من طبق آموزش گیت، پکیج ها و نصب کردم و به پروژه اضافه کردم
تنظیمات فایل Startup هم قرار دادم
ولی در اجرا خطا میده
GenericArguments[0], 'SeyedMarket.DomainClasses.Context.ApplicationDbContext', on 'DynamicAuthorization.Mvc.Ui.Services.IdentityService`4[TDbContext,TUser,TRole,TKey]' violates the constraint of type 'TDbContext'.'

Building with .Net 5

Hello can you please share an update on the .Net 5 / EF 5 build, its giving built in security with change tracking automatically

Dynamic Claims

Hello, can you share some suggestion on how to do secure data in the same role across groups, I was thinking claims might be good.

For e.g. when you have managers in the same role, but you want to limit the data to only their geographic areas so they don't see other financial data.

Thanks

I can create the role in asp.net core 5

I can create the role in asp.net core 5
Please help me how to fix the error

The errors on "var controllers = (IEnumerable<MvcControllerInfo>)ViewData["Controllers"];"

An unhandled exception occurred while processing the request.
InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List1[DynamicAuthorization.Mvc.Core.MvcControllerInfo]' to type 'System.Collections.Generic.IEnumerable1[DynamicAuthorization.Models.MvcControllerInfo]'.
AspNetCore.Views_Role_Create.ExecuteAsync() in Create.cshtml, line 5

image

How to implement in razor page

i have created new MVC core 3.1 application with razor identity. when i run the application and i'm getting this error:

InvalidCastException: Unable to cast object of type 'Microsoft.AspNetCore.Mvc.RazorPages.CompiledPageActionDescriptor' to type 'Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor'.
SchoolManagementSystem.ExtentionMethods.DynamicAuthorizationFilter.IsProtectedAction(AuthorizationFilterContext context) in DynamicAuthorizationFilter.cs, line 66

please guide me, how can i implement DynamicRoleBasedAuthorizationNETCore in razor pages as well.

Admin User

This is exactly what I was looking for, but one hitch to get started - which is the Admin user? Can't seem to find where you defined it.

Menu Lists Based on Role/Claim

Hi, couple of ideas:

See Menu/View in admin page: it would be nice to have a view of which menus are visible to which roles and which claims.
Also the samples from manual are not working with this master release.

An unhandled exception occurred while processing the request

Hi @mo-esmp Thanks for this excellent repository. Some initial small problems I faced are :

I am using .Net Core 6.0

  1. After successful login you can log out (error - Access denied You do not have access to this resource) because you do not have any default access and to give access you have to manually disable the restrictions (as comments [Authorize] in controllers & all required secure-content asp-area="" asp-controller="Role" asp-action="Index" in _Layout.cshtml).

  2. I found that when creating role without any access it is throwing the following errors and same error when we edit the role and try to give the access from access list
    ArgumentNullException: Value cannot be null. (Parameter 'value')
    Newtonsoft.Json.Utilities.ValidationUtils.ArgumentNotNull(object value, string parameterName)
    Newtonsoft.Json.JsonConvert.DeserializeObject(string value, Type type, JsonSerializerSettings settings)
    Newtonsoft.Json.JsonConvert.DeserializeObject(string value, JsonSerializerSettings settings)
    Newtonsoft.Json.JsonConvert.DeserializeObject(string value)
    eis4.Controllers.RoleController.Edit(string id) in RoleController.cs

  •       ViewData["Controllers"] = _mvcControllerDiscovery.GetControllers();
          var role = await _roleManager.FindByIdAsync(id);
          if (role == null)
              return NotFound();
          var viewModel = new RoleViewModel
          {
              Name = role.Name,
              SelectedControllers = JsonConvert.DeserializeObject<IEnumerable<MvcControllerInfo>>(role.Access)
          };
          return View(viewModel);
    

lambda_method364(Closure , object )

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.