score:1

Accepted answer

you could setup a policy to do it : this just reads a string array from "allowedgroups" in appsettings.json but it demonstrates the fundamentals.

{
  "allowedgroups": [ "administrator", "moderator" ]
}
public class hasrolesfromconfigrequirement : iauthorizationrequirement
{
    internal string[] allowedgroups;
    public hasrolesfromconfigrequirement(string[]? allowedgroups) => this.allowedgroups = allowedgroups;
}
public class hasrolesfromconfighandler : authorizationhandler<hasrolesfromconfigrequirement>
{
    protected override task handlerequirementasync(
        authorizationhandlercontext context,
        hasrolesfromconfigrequirement requirement)
    {
        var rolesrequired = requirement.allowedgroups;
        if (rolesrequired is null)
        {
            context.fail();
        }
        else
        {
            var hasrequiredrole = rolesrequired.where(role => context.user.isinrole(role)).any();
            if(hasrequiredrole)
            {
                context.succeed(requirement);
            }
            else
            {
                context.fail();
            }
        }
        return task.completedtask;
    }
}
public static class authorizationoptionspolicyextensions
{
    public static void addpolicies(this iservicecollection services, iconfiguration configuration)
    {
        services.addscoped<iauthorizationhandler, hasrolesfromconfighandler>();
        services.addauthorizationcore(options => options.configurepolicies(configuration));
    }

    public static authorizationoptions configurepolicies(this authorizationoptions options, iconfiguration configuration)
    {
        var localconfiguration = configuration.get<localconfiguration>();
        options.addpolicy("hasarequiredrole", policy => policy.requirements.add(new hasrolesfromconfigrequirement(localconfiguration.allowedgroups)));
        return options;
    }

}
<authorizeview policy="hasarequiredrole">
    <div>
        has a required role
    </div>
</authorizeview>
@page "/fetchdata"
@attribute [authorize(policy = "hasarequiredrole")]
...
[authorize(policy = "hasarequiredrole")]
public class weatherforecastcontroller : controllerbase

a .net6(rc1) repo.

i would personally look at claim based permissions. this way you can assign application resources to a claim. then dynamically assign the claims to roles or individuals.

score:1

attributes are embedded in the assembly at build time. once the project/dll is built, you cannot change the value again.

you need to perform runtime authorization. since you're trying to check roles, inject the configuration and check if the user has any of the roles:

@inject iconfiguration configuration
var isallowed = configuration.getsection("allowedgroups")
    .get<string[]>()
    .any(group => user.isinrole(group));

further info


Related Query

More Query from same tag