Вы должны использовать Policy
и написать свой AuthorizationHandler
.
Вот пример, как вы можете это сделать:
appsettings.json
{
"Auth": {
"Role": "User"
}
}
startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.Build();
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthorization(cfg =>
{
cfg.AddPolicy("dynamicRole", b => b.Requirements.Add(new DynamicRole()));
});
services.AddScoped<IAuthorizationHandler, DynamicRoleHandler>();
services.Configure<AuthorizationOptions>(Configuration.GetSection("Auth"));
}
}
DynamicRole.cs
public class DynamicRole : IAuthorizationRequirement
{
}
AuthorizationOptions.cs
public class AuthorizationOptions
{
public string Role { get; set; }
}
DynamicRoleHandler.cs
public class DynamicRoleHandler : AuthorizationHandler<DynamicRole>
{
private readonly AuthorizationOptions _options;
public DynamicRoleHandler(IOptionsMonitor<AuthorizationOptions> options)
{
_options = options.CurrentValue;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, DynamicRole requirement)
{
if (context.User.IsInRole(_options.Role))
{
context.Succeed(requirement);
}
else
{
context.Fail();
}
return Task.CompletedTask;
}
}
TestController.cs
public class TestController : Controller
{
[Authorize(policy: "dynamicRole")]
public string Test()
{
return "Hello World!";
}
}