Coder Social home page Coder Social logo

Comments (8)

EduardoPires avatar EduardoPires commented on May 21, 2024

Did you registered the user by the application?
Did you validate the data in the Claims table?

from equinoxproject.

digounet avatar digounet commented on May 21, 2024

Yes. There're two records in user claims table.

from equinoxproject.

EduardoPires avatar EduardoPires commented on May 21, 2024

I updated to the ASP.NET 2.0 version and tested the authorization rules. It's working fine.

from equinoxproject.

digounet avatar digounet commented on May 21, 2024

Hello Eduardo,

Did you registered the user by the application? YES
Did you validate the data in the Claims table? YES

In claim table I have:

  Id ClaimType ClaimValue UserId
  9 Parks Write 925dbffb-731d-40e8-b4e4-d4eb4986e07c
  10 Parks Read 925dbffb-731d-40e8-b4e4-d4eb4986e07c
  11 Parks Remove 925dbffb-731d-40e8-b4e4-d4eb4986e07c

In Users table:

  Id AccessFailedCount ConcurrencyStamp Email EmailConfirmed LockoutEnabled LockoutEnd NormalizedEmail NormalizedUserName PasswordHash PhoneNumber PhoneNumberConfirmed SecurityStamp TwoFactorEnabled UserName
  925dbffb-731d-40e8-b4e4-d4eb4986e07c 0 6657e43b-4ad9-408f-978a-c486339d5404 [email protected] False True (NULL) [email protected] [email protected] AQAAAAEAACcQAAAAEOnnYPjyqBo9hMqz77agLaMS15b7zh8LQduamBzCqdsy1gFTGSEnwBAxDWiRb6xiHg== (NULL) False 41b74c38-6fa1-4381-a386-ebb75df55b56 False [email protected]

Controller Method:

        [HttpGet]
        [Authorize(Policy = "CanReadParkData")]
        [Route("park-management/list-all")]
        public IActionResult Index()
        {
            return View(_parkAppService.GetAll());
        }

Startup.cs

   public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

            if (env.IsDevelopment())
            {
                builder.AddUserSecrets<Startup>();
            }

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }
        
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(o => {
                    o.LoginPath = new PathString("/login");
                    o.AccessDeniedPath = new PathString("/home/access-denied");
                })
                .AddFacebook(o =>
                {
                    o.AppId = Configuration["Authentication:Facebook:AppId"];
                    o.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
                })
                .AddGoogle(googleOptions =>
                {
                    googleOptions.ClientId = Configuration["Authentication:Google:ClientId"];
                    googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
                }); ;

            services.AddMvc();
            services.AddAutoMapper();

            services.AddAuthorization(options =>
            {
                options.AddPolicy("CanWriteParkData", policy => policy.Requirements.Add(new ClaimRequirement("Parks","Write")));
                options.AddPolicy("CanRemoveParkData", policy => policy.Requirements.Add(new ClaimRequirement("Parks", "Remove")));
                options.AddPolicy("CanReadParkData", policy => policy.Requirements.Add(new ClaimRequirement("Parks", "Read")));
            });

			// Configure Identity
			services.Configure<IdentityOptions>(options =>
			{
				// Password settings
				options.Password.RequireDigit = true;
				options.Password.RequiredLength = 6;
				options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = false;
				options.Password.RequireLowercase = false;

				// Lockout settings
				options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
				options.Lockout.MaxFailedAccessAttempts = 10;

				// User settings
				options.User.RequireUniqueEmail = true;
			});            

            // Adding MediatR for Domain Events and Notifications
            services.AddMediatR(typeof(Startup));

            // .NET Native DI Abstraction
            RegisterServices(services);
        }

        public void Configure(IApplicationBuilder app,
                                      IHostingEnvironment env,
                                      ILoggerFactory loggerFactory,
                                      IHttpContextAccessor accessor)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                //app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=welcome}/{id?}");
            });
        }

        private static void RegisterServices(IServiceCollection services)
        {
            // Adding dependencies from another layers (isolated from Presentation)
            NativeInjectorBootStrapper.RegisterServices(services);
        }
    }

from equinoxproject.

thiagolunardi avatar thiagolunardi commented on May 21, 2024

@digounet What you have at AspNetUserClaims table?

from equinoxproject.

EduardoPires avatar EduardoPires commented on May 21, 2024

Try putting all together like:
Write, Remove, Create ......

from equinoxproject.

digounet avatar digounet commented on May 21, 2024

@EduardoPires @thiagolunardi Solved:

In ClaimsRequirementHandler i've changed the method HandleRequirementAsync to:

```
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                   ClaimRequirement requirement)
    {        
        var claim = context.User.Claims.FirstOrDefault(c => c.Type == requirement.ClaimName && c.Value == requirement.ClaimValue);
        if (claim != null)
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
The error occur because the original implementation gets only the first result of the claims table:

`var claim = context.User.Claims.FirstOrDefault(c => c.Type == requirement.ClaimName);`


from equinoxproject.

EduardoPires avatar EduardoPires commented on May 21, 2024

That's Right! the original implementation get only the first row.

from equinoxproject.

Related Issues (20)

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.