Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

181
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda