Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
Is it possible to conditionally associate an attribute onto a class based on boolean value loaded from appsettings.json

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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();
        }
    });
});
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!