Search code examples
c#asp.net-coreasp.net-core-identityasp.net-core-2.1

ASP.NET Core 2.1: Razor Pages - role based authorisation not working


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("RequireAdminRole", policy => 
            policy.RequireAuthenticatedUser().RequireRole("Admin"));
    });

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

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.

What am I doing wrong?

UPDATE

If I remove the AuthorizePage and use GetUsersInRoleAsync("Admin") in the About.cshtml.cs page OnGet method, then output the UserName property in the About.cshtml page, the admin user is displayed. So, not sure why the AuthorizePage is not working.

UPDATE 29-May-2017

My source code is in this Github Resository


Solution

  • I've managed to find the solution:

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

    I think it works as follows:

    • AddItentity - Sets up identity.
    • AddDefaultUI - Use new Razor Class Library UI.
    • AddDefaultTokenProviders - Needed for two factor authentication.