Role Based Authorization not working .NET Core 3.0

167 Views Asked by At

Role-Based Authorization not working in my code, Please guide me if i am missing anything. My project is on .net core 3.0 framework.

Authentication is working fine but authorization is not working.

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.Configure<CookieTempDataProviderOptions>(options =>
        {
            options.Cookie.IsEssential = true;
        });
        services.AddDbContextPool<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>(config =>
        {
            config.User.RequireUniqueEmail = true;    // ���������� email
            config.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 -._@+"; 
            config.SignIn.RequireConfirmedEmail = false;
        }).AddEntityFrameworkStores<ApplicationDbContext>()
          .AddClaimsPrincipalFactory<MyUserClaimsPrincipalFactory>()
          .AddDefaultTokenProviders();

        services.AddMvc(config => {
            var policy = new AuthorizationPolicyBuilder()
                            .RequireAuthenticatedUser()
                            .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
        }).AddRazorPagesOptions(options =>
            {
                options.Conventions.AuthorizeFolder("/");

                options.Conventions.AllowAnonymousToPage("/Error");
                options.Conventions.AllowAnonymousToPage("/Account/AccessDenied");
                options.Conventions.AllowAnonymousToPage("/Account/ConfirmEmail");
                options.Conventions.AllowAnonymousToPage("/Account/ExternalLogin");
                options.Conventions.AllowAnonymousToPage("/Account/ForgotPassword");
                options.Conventions.AllowAnonymousToPage("/Account/ForgotPasswordConfirmation");
                options.Conventions.AllowAnonymousToPage("/Account/Lockout");
                options.Conventions.AllowAnonymousToPage("/Account/Login");
                options.Conventions.AllowAnonymousToPage("/Account/LoginWith2fa");
                options.Conventions.AllowAnonymousToPage("/Account/LoginWithRecoveryCode");
                options.Conventions.AllowAnonymousToPage("/Account/Register");
                options.Conventions.AllowAnonymousToPage("/Account/ResetPassword");
                options.Conventions.AllowAnonymousToPage("/Account/ResetPasswordConfirmation");
                options.Conventions.AllowAnonymousToPage("/Account/SignedOut");
            })
            .SetCompatibilityVersion(CompatibilityVersion.Latest);
        
        services.AddControllersWithViews().AddRazorRuntimeCompilation();
        services.Configure<MailManagerOptions>(Configuration.GetSection("Email"));

        if (Configuration["Email:EmailProvider"] == "SendGrid")
        {
            services.Configure<SendGridAuthOptions>(Configuration.GetSection("Email:SendGrid"));
            services.AddSingleton<IMailManager, SendGridMailManager>();
        }
        else
        {
            services.AddSingleton<IMailManager, EmptyMailManager>();
        }

        services.AddScoped<ProfileManager>();

    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Dashboards}/{action=Index}/{id?}");

        });

    }
}

and i am using Authorize in controller, i added admin role to my userid,i Verified in database my userid is mapped with Admin role, [Authorize] is working properly but after giving role in the parameter always returns in AccessDenied

[HttpGet]
[Authorize(Roles = "Admin")]
public IActionResult CreateRole()
{
    return View();
}

MyUserClaimsPrincipalFactory Code:

public class MyUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser>
    {
        private readonly ApplicationDbContext _context;
        public MyUserClaimsPrincipalFactory(UserManager<ApplicationUser> userManager,IOptions<IdentityOptions> optionsAccessor, ApplicationDbContext context)
                : base(userManager, optionsAccessor)
        {
            _context = context;
        }

        protected override async Task<ClaimsIdentity> GenerateClaimsAsync(ApplicationUser user)
        {
            var identity = await base.GenerateClaimsAsync(user);
            return identity;
        }
    }
0

There are 0 best solutions below