Search code examples
c#asp.net-corerazor-pages.net-5

Restricting folder access by role in Razor Pages


I've been searching and searching but cannot get a straight forward answer to this. (Most of the answers I do find are outdated.)

It looks like I can restrict access to a razor page using the Authorize attribute on my page class.

[Authorize(Roles = "Admin")]

But, using the current version of Razor Pages, how can I restrict an entire folder or Area?


Solution

  • It's frustrating that this stuff appears to change with every release. This makes it hard to know if you're looking at the right documentation.

    But this appears to be approach needed with the latest version, and it works for me.

    ConfigureServices()

    services.AddAuthorization(options =>
    {
        // Create policies
        options.AddPolicy("Staff", p => p.RequireRole(Role.Staff));
        options.AddPolicy("Admin", p => p.RequireRole(Role.Admin));
    });
    
    // Set authorizations
    services.AddRazorPages(options =>
    {
        // Requires staff role for all pages (not including areas)
        options.Conventions.AuthorizeFolder("/", "Staff");
    
        // Set authorization for areas (looks like no way to do all areas at once)
        options.Conventions.AuthorizeAreaFolder("Admin", "/", "Admin");
        options.Conventions.AuthorizeAreaFolder("Leasing", "/", "Staff");
        options.Conventions.AuthorizeAreaFolder("Repair", "/", "Staff");
        options.Conventions.AuthorizeAreaFolder("Storage", "/", "Staff");
        options.Conventions.AuthorizeAreaFolder("Transloading", "/", "Staff");
    
        // Anonymous pages
        options.Conventions.AllowAnonymousToPage("/Index");
        options.Conventions.AllowAnonymousToPage("/Error");
    });