Home > OS >  Is it possible to conditionally associate an attribute onto a class based on boolean value loaded fr
Is it possible to conditionally associate an attribute onto a class based on boolean value loaded fr

Time:11-30

I have some page model classes, and would like to make the pages controlled by these models to either be anonymously accessible or only viewable if the user is authenticated based on a boolean conditional that's configured in my appsettings.json file. Something like the following (the syntax is obviously incorrect, but I hope it demonstrates my intention clearly).

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

boolCondition ? [Authorize] : [AllowAnonymous]
public class IndexModel : PageModel
{
...
}

Based on this answer here, even though it's a bit old, I'm not actually certain if what I'm looking to do is even possible in C#. And to be frank, that answer is a bit over my head, so I don't know how applicable it is to my situation.

Another potential approach that came to mind was to create my own custom attribute class, and in there conditionally return either the AuthorizeAttribute or AllowAnonymousAttribute based on the boolean condition. But even then, I'm still unsure if that'll work, since that seems to still depend on a runtime condition.

Any help and advice is appreciated.

CodePudding user response:

By using an authorization policy, you can change what that means on startup (or within an IConfigureOptions<AuthorizationOptions> service).

You can either change the default policy for all [Authorize] attributes;

services.AddAuthorization(o => {
    var builder = new AuthorizationPolicyBuilder();
    if (<something>){
        builder.RequireAssertion(c => true);
    }else{
        builder.RequireAuthenticatedUser();
    }
    o.DefaultPolicy = builder.Build();
});

Or introduce a new policy that only applies to some [Authorize(Policy="Name")].

services.AddAuthorization(o => {
    o.AddPolicy("Name", builder => {
        if (<something>){
            builder.RequireAssertion(c => true);
        }else{
            builder.RequireAuthenticatedUser();
        }
    });
});
  • Related