Search code examples
c#asp.net-corerazoridentity

Different authorization for one folder page than for the rest of the folder in ASP.NET Core Razor


Using ASP.NET Core identity, I'd like to allow an authorized user ability to change their password, but require the policy "Admin" access to access the other Account Manage pages.

However, this doesn't work:

services.AddRazorPages(
    options =>
      {        
          options.Conventions.AuthorizeAreaPage("Identity", "/Account/Manage/ChangePassword");
          options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage", "Admin");
      }

My assumption is that you can't do this in Razor, the Admin policy restriction for the entire folder overrides the less restrictive requirement for just the ChangePassword page.

I've tried putting the ChangePassword statement last, and using a route change

 .AddRazorPagesOptions(options =>
 {
     options.Conventions.AddAreaPageRoute("Identity","/Account/Manage/ChangePassword", "changepassword");
 });

to "trick" it (along with options.Convetions.AuthorizePage("/changepassword") but that also results in the "Admin" policy authorization requirement.

Is there a way around this (like scaffolding the ChangePassword.cshtml.cs page and using [Authorize] above the model class declaration)?


Solution

  • You could solve this by specify a "MyDefaultPolicy" when setting AuthorizeAreaPage like following:

    services.AddRazorPages(
        options =>
        {
            options.Conventions.AuthorizeAreaPage("Identity", "/Account/Manage/ChangePassword", "MyDefaultPolicy");
            options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage", "Admin");
        });
    
    services.AddAuthorization(options =>
    {
        options.AddPolicy("MyDefaultPolicy", policyBuilder => policyBuilder.RequireAuthenticatedUser());
    });