mo-esmp / DynamicRoleBasedAuthorizationNETCore

Dynamic Role-Based Access Control for ASP.NET Core MVC and Web API
GNU General Public License v3.0
451 stars 94 forks source link

accessList is always returning null #21

Closed tgerevini closed 3 years ago

tgerevini commented 3 years ago

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

mo-esmp commented 3 years ago

Hi @tgerevini What store type do you use? JSON or SQLServer? If roleAccess object is not null then after calling await _roleAccessStore.AddRoleAccessAsync(roleAccess);, it should be stored, check the store to see values are saved or not. It would be a great help if you provide a project on Github or send me by email that demonstrates the issue.

tgerevini commented 3 years ago

I'm using SQLServer. I got you an access to the project on github, i really apreciate your help! https://github.com/solutions-atv/FrameworkBase

i'm going to look into the roleAccess object and see it i's storing the value, if i still dont manage to make it work, i'll keep you updated, thanks a lot! The default user and pwd is admin, cheers!

ps.: I changed the startup to use .AddJsonStore() and it worked, but i need to be saved on the database.

I also noticed that the DynamicAuthorizationOptions class doesn't seen to be updated:

#region Assembly DynamicAuthorization.Mvc.Core, Version=1.1.1.0, Culture=neutral, PublicKeyToken=null
// C:\Users\gerev\.nuget\packages\dynamicauthorization.mvc.core\1.1.1\lib\net5.0\DynamicAuthorization.Mvc.Core.dll
#endregion

namespace DynamicAuthorization.Mvc.Core.Models
{
    public class DynamicAuthorizationOptions
    {
        public DynamicAuthorizationOptions();

        public string DefaultAdminUser { get; set; }
    }
}

I noticed when i tried to implement the User Role functionality today

mo-esmp commented 3 years ago

I will check the project soon and I will update you.

mo-esmp commented 3 years ago

I have debugged your project and everything worked as expected and I couldn't re-produce malfunctionality you mentioned.

d2 d1

tgerevini commented 3 years ago

I noticed i dont have this table in my database... did you create RoleAccess table?

mo-esmp commented 3 years ago

This table will be created automatically when the project has started

tgerevini commented 3 years ago

Hmm that's probabily the problem, it's not being created in my environment, only the other ones

image

mo-esmp commented 3 years ago

Run the application with dotnet run and check out the logs on console output to see if any error occurs during table creation.

tgerevini commented 3 years ago

image

: \ 2 - Sources \ git \ solutions-atv \ FrameworkBase \ Directory.Build.targets (70,5): error MSB4801: task factory "CodeTaskFactory" is not supported in the .NET Core version of MSBuild. [D: \ 2 - Sources \ git \ solutions-atv \ FrameworkBase \ FrameworkBase.Domain \ FrameworkBase.Domain.csproj] D: \ 2 - Sources \ git \ solutions-atv \ FrameworkBase \ Directory.Build.targets (70,5): error MSB4175: Task factory "CodeTaskFactory" was not loaded from assembly "C: \ Program Files \ dotnet \ sdk \ 5.0.201 \ Microsoft.Build.Tasks.Core.dll ". A task factory must return a value for a "TaskType" property. [D: \ 2 - Sources \ git \ solutions-atv \ FrameworkBase \ FrameworkBase.Domain \ FrameworkBase.Domain.csproj]

maybe that's cause i'm using .net core 5.0?

mo-esmp commented 3 years ago

No, it's not related to .NET Core 5.0 because I successfully created a role and access-list with your project. Run the project with VS and instead of IIS Express choose FrameworkBase.UI

Screenshot 2021-03-24 031214

Inside the console, If any errors related to table creation occur, there should be an error message that starts with:

Screenshot 2021-03-24 031152

tgerevini commented 3 years ago

ohh i got it now, thanks! image

Now i have a clue on the problem, gonna search for a solution

mo-esmp commented 3 years ago

There is a problem with your connection string, check if there is any problem with your connection string.

https://stackoverflow.com/q/8243008/1385614 https://stackoverflow.com/q/30550679/1385614

tgerevini commented 3 years ago

Weird, cause the rest of the tables were created.... But i got it working! These are the steps that i followed:

1) Changed connection string authentication - from Trusted Connection to Standard Security. 2) Restarting MSSQLSERVER process

It still gave me collation error, but it created the table.

image

tgerevini commented 3 years ago

Now i'm facing problems trying to configure UserRole controller without using the UI. Do you have any walkthrough?

I think i need to set this on statup right? image

But this "DynamicAuthorization" class got no such properties and i'm using the latest version:

image

mo-esmp commented 3 years ago

Check the manual branch for a walkthrough: https://github.com/mo-esmp/DynamicRoleBasedAuthorizationNETCore/tree/manual

Now i'm facing problems trying to configure UserRole controller without using the UI. Do you have any walkthrough?

I think i need to set this on statup right? image

No, you don't need this. just take a look at the UI project to see how to implement it. Also in the blow sample, I implemented UI functionallity without using UI package: https://github.com/mo-esmp/DynamicRoleBasedAuthorizationNETCore/tree/master/samples/netcore3.x/SampleMvcWebApp

tgerevini commented 3 years ago

Thanks! It's almost working lol... now users / roles and access list is working... The problem i'm facing now is that i added the tagHelper but the application completely ignores this class.

image

I added the secure-content tags as told, but the menu links are always visible no matter what access i add or remove to role.

image

mo-esmp commented 3 years ago

I guess you forgot to import your project namespace into the _ViewImports.cshtml file https://github.com/mo-esmp/DynamicRoleBasedAuthorizationNETCore/blob/master/samples/net5/SampleMvcWebWithUi/Views/_ViewImports.cshtml

tgerevini commented 3 years ago

Perfect! damn i tried to import on shared view lol, thanks!

Now, is it possible to change the access denied view?

image

mo-esmp commented 3 years ago

I just return ForbidResult when a user does not have access to a resource. You should handle the error 403 within your application.

This link might help you https://stackoverflow.com/a/52625797/1385614

tgerevini commented 3 years ago

Thanks! Now it's working perfectly!