是否有办法根据配置设置启用和禁用授权要求(使用authorize属性)?
基本上我想用[Authorize]
属性来装饰控制器,但我希望有一个选项可以从配置中禁用它(因此不需要更改代码)。
我试着查看AuthorizationHandler
,但看起来它建立在authorize属性之上,从某种意义上说它首先检查用户是否被授权,然后将执行传递给我的代码:
namespace MeasureThat.Net.Logic.Web
{
/// <summary>
/// Class to replace unconditional authorization attribute
/// Will allow to disable authorize attribute from config
/// </summary>
public class ConfigurableAuthorizationHandler : AuthorizationHandler<ConfigurableAuthorizationRequirement>
{
private readonly SignInManager<ApplicationUser> signInManager;
public ConfigurableAuthorizationHandler(SignInManager<ApplicationUser> signInManager)
{
this.signInManager = signInManager;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
ConfigurableAuthorizationRequirement requirement)
{
if (requirement.AllowGuestsToCreateBenchmarks)
{
// No further checks need, guests can proceed
context.Succeed(requirement);
}
else
{
// Need to make sure that user authenticated
if (!signInManager.IsSignedIn(context.User))
{
// Reject, not signed in
context.Fail();
}
}
return Task.FromResult(0);
}
}
}