【问题标题】:Require all policies by default in Api Controllers在 API 控制器中默认需要所有策略
【发布时间】:2020-06-19 11:45:03
【问题描述】:

我不知道这听起来是否愚蠢,但我有点担心控制器中的授权是如何完成的。

现在我正在使用 [Authorize] 属性来保护我的端点。但是,我有点担心我忘记添加策略并且任何人都可以访问端点。

有什么方法可以默认应用所有策略,只需为您要允许的策略添加一个属性?

【问题讨论】:

  • 授权策略包含一个或多个要求。它在Startup.ConfigureServices method 中注册为授权服务配置的一部分。然后使用带有策略名称的[Authorize(Policy = "PolicyName")] 属性将策略应用于控制器。参考Policy-based authorization in ASP.NET Core
  • 我知道这是怎么回事。我就是这样使用它的。但是,我更喜欢一些默认提供安全性的东西。我的意思是,没有 [Authorize] 属性的控制器应该禁止访问任何操作。然后,稍后我将向方法添加一个属性,以表明我希望允许具有策略 X 的用户使用该方法。默认情况下,控制器允许不受限制地访问任何控制器操作。我只是希望它是相反的方式。

标签: asp.net-core authorization asp.net-authorization


【解决方案1】:

在 Asp.Net Core 2.x 中,您可以使用过滤器来设置全局授权属性:

services.AddMvc(options =>
{
    // This requires an authenticated user for all controllers/actions, 
    // except when at controller/action the [AllowAnonymous] attribute is set.
    var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
    options.Filters.Add(new AuthorizeFilter(policy));

    // In the same way you can set a global AntiforgeryToken
    options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

在 Asp.Net core 3.x 中引入了端点路由。启用后,您可以设置每个端点,如migration documentation 中所述:

services.AddControllersWithViews(options =>
{
    options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
}).SetCompatibilityVersion(CompatibilityVersion.Version_3_0)

可能的端点配置:

app.UseEndpoints(endpoints =>
{
    // equivalent of [Authorize] attribute on each controller:
    endpoints.MapDefaultControllerRoute().RequireAuthorization();
});

未询问,但推荐:Automatically validate antiforgery tokens for unsafe HTTP methods only

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    • 2019-08-25
    相关资源
    最近更新 更多