我尝试定义一个授权策略,以应用于我所有控制器的所有方法。我正在尝试按照guidelines given here, in "Authorization for specific endpoints" subsection替换我之前的AuthorizeFilter
,但它不起作用。
在我的Startup
中,我有:
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute().RequireAuthorization();
});
在ConfigureServices
中
services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
.AddAzureADBearer(options => this.Configuration.Bind("AzureAd", options));
services.AddAuthorization(options =>
{
options.DefaultPolicy = new AuthorizationPolicyBuilder()
.AddRequirements(new MyRequirement(MyParams))
.Build();
});
(...)
services.AddTransient<IAuthorizationHandler, MyAuthorizationHandler>();
我有一个要求:
public class MyRequirement : IAuthorizationRequirement
{
public EntityType MyParams { get; private set; }
public MyRequirement(MyParams myParams) { MyParams = myParams; }
}
和一个处理程序:
public class MyAuthorizationHandler : AuthorizationHandler<MyRequirement>
{
private readonly ILogger<MyAuthorizationHandler> logger;
private readonly IHttpContextAccessor httpContextAccessor;
public MyAuthorizationHandler(IHttpContextAccessor httpContextAccessor, ILogger<MyAuthorizationHandler> logger)
{
this.httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
this.logger = logger;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MyRequirement requirement)
{
---> Some things. I don't get here when I debug.
}
}
在我的控制器中,我没有放置任何装饰器,因为我希望将此授权策略应用于我的所有方法,这就是我重写DefaultPolicy
的原因。
如果我进行调试,我不会像预期的那样在处理程序处停止。实际上,如果我在控制器中放置一个装饰器[Authorize]
,我就到此为止了,但正如我前面提到的,我试图避免在所有控制器中都编写这个装饰器。
为什么不工作?谢谢!
发布于 2019-12-28 01:30:33
我的理解是,即使使用默认策略,也需要[Authorize]
属性。当我需要以这种方式保护我的所有端点时,我通常会做的是创建一个具有此属性的抽象基本控制器,然后让我的其他控制器继承它。
例如:
基本控制器
[Authorize]
public abstract class MyBaseController : Controller //use Controller for mvc controller or ControllerBase for api controller
{
//base controller methods and properties
}
其他控制器:
public class MyOtherController : MyBaseController
{
//controller methods and properties
}
https://stackoverflow.com/questions/59503646
复制相似问题