gpt4 book ai didi

.net-core - .NET Core 覆盖特定操作的 Controller 级别授权属性

转载 作者:行者123 更新时间:2023-12-03 21:22:05 25 4
gpt4 key购买 nike

这是一个示例 Controller 来解释这种情况

[Authorize]
public class AccountController : ControllerBase
{
[AllowAnonymous]
[Authorize(Policy = "SpecificPolicy")]
public string MethodA() {}

public string MethodB() {}
}
  • MethodA 只能通过“SpecificPolicy”进行授权。
  • MethodB 应该通过 Authorized 属性授权

  • 我遇到的问题是,如果我删除 AllowAnonymous 属性,则 Controller 上的 Authorize 优先,我不希望 MethodA。

    当我为 MethodA 保留 AllowAnonymous 时,将忽略 Authorize(Policy = "SpecificPolicy") 。

    最佳答案

    When I keep AllowAnonymous for MethodA then Authorize(Policy = "SpecificPolicy") is ignored.


    [AllowAnonymous]绕过所有其他授权属性。当你同时拥有其他授权属性时,其他所有属性都是 忽略 ,甚至其他属性都是更具体的方法级别。

    例如:

    [AllowAnonymous]
    public class DashboardController : Controller
    {
    [Authorize]
    public IActionResult Index()
    {
    return View();
    }
    }
    /dashboard将是开放/公开的。

    The issue I'm having is that if I remove the AllowAnonymous attribute then Authorize on the controller takes precedence which I don't want for MethodA.



    当您有多个授权属性时,在调用该方法之前需要满足所有这些属性。在你的情况下,两个 [Authorize][Authorize(Policy = "SpecificPolicy")]必须通过才能获得访问权限。

    如果您不想要 [Authorize]要获得优先权,您只能将其应用于方法 B:

    public class AccountController : ControllerBase
    {
    [Authorize(Policy = "SpecificPolicy")]
    public string MethodA() {}

    [Authorize]
    public string MethodB() {}
    }

    I want to avoid putting specific [Authorize] attributes on actions since that Controller has lots of actions but a single action that has it's own authorize rule.



    那么这可能是您将 MethodA 拆分为 的好时机。地区 .

    例如:

    你还有 [Authorize]在您的 AccountController ,但只需取出MethodA:

    [Authorize]
    public class AccountController : ControllerBase
    {
    public string MethodB() {}
    }

    然后为 MethodA 创建一个区域:

    [Area("specific")]
    [Authorize(Policy = "SpecificPolicy")]
    public abstract class SpecificControllerBase : ControllerBase
    { }

    public class AccountController : SpecificationControllerBase
    {
    public string MethodA() {}
    }

    最后,您需要在您的 Startup.cs 中注册区域路线:

    app.UseMvc(routes =>
    {
    ...

    routes.MapRoute(
    name: "areaRoute",
    template: "{area:exists}/{controller=dashboard}/{action=index}/{id?}");

    routes.MapRoute(
    name: "default",
    template: "{controller=home}/{action=index}/{id?}");
    });

    关于.net-core - .NET Core 覆盖特定操作的 Controller 级别授权属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52729492/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com