Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

ASP.NET Core 2.1 - Can't get role based authentication to work

$
0
0

My Razor Pages app is configured as follows. Startup.cs contains:

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlite(
                    Configuration.GetConnectionString("DefaultConnection")));

            services.AddDefaultIdentity<IdentityUser>()
                .AddRoles<IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddAuthorization(options =>
            {
                options.AddPolicy("RequireAdministratorRole",
                    policy => policy.RequireRole("Admin"));
            });

            services.AddMvc()
               .AddRazorPagesOptions(options =>
                {
                    options.Conventions.AuthorizePage("/About", "RequireAdministratorRole");
                })
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseAuthentication();

            app.UseMvc();
        }

I have a user with the "Admin" role. When the user is logged in and accesses the "About" page, I get the following:

Access denied

You do not have access to this resource.

Note that ASP.NET Core 2.1 uses a Razor Class Library for the UI.

I've added code to the index page that shows, when the admin user is logged in, the following:

User.IsInRole("Admin"): False

User's roles using GetRolesAsync:

  • Admin

The above seem to conflict.

What am I doing wrong?

The full source code is available on Github: Github.


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>