【问题标题】:ASP.NET Authentication POST PolicyASP.NET 身份验证 POST 策略
【发布时间】:2019-06-12 14:15:24
【问题描述】:

我目前正在开发 POST 控制器。过去,我在控制器本身中处理过有关身份验证的逻辑,如下所示:

    [HttpPost]
    public HttpResponseMessage Post([FromBody] Foo foo)
    {
        if (foo.bar !== user.bar){
            return;
    }

我不是最好的 c# 程序员,所以不知道应该如何处理。在研究时,我偶然发现了政策。所以我已经在控制器上方使用了一个 [Authenticated] 标签,但是基于此示例中的 foo.bar 是否与 me.bar 相同,我不允许发布此帖子。 (所以经过身份验证的标签是用于身份验证但我想更改授权)

我是否可以创建一个 [Policy=("fooPoster")] 并使用其中的帖子正文来确定我是否有权访问该帖子,或者我只能访问全局状态来判断?

【问题讨论】:

  • @Jabberwocky 这就是我遇到的,是的。这似乎是针对 asp.net 核心的,但我也看到它有所修改。尽管如此,我对此的经验较少,并且无法得出结论是否可以将帖子的正文用于策略,除了您可以为其提供一个功能(但将授权逻辑放在其他地方可能是多余的比在控制器中)
  • 谢谢!尝试将其放入其中似乎有点矫枉过正,因为它不仅仅是一个现场比较!

标签: asp.net


【解决方案1】:

您可以尝试自定义授权。参考下面的代码。

    [HttpPost]
    [CustomAuthorization(Foo.bar)]
    public HttpResponseMessage Post([FromBody] Foo foo)
    {
        if (foo.bar !== user.bar)
        {
            return;
        }
    }



    public class CustomAuthorizationAttribute : AuthorizeAttribute
{
    private readonly string allowedroles;
    public CustomAuthorizationAttribute(string roles)
    {
        this.allowedroles = roles;
    }
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        bool authorize = false;
        if (Me.bar != allowedroles)
        {
            authorize = true;
        }
        return authorize;
    }
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new HttpUnauthorizedResult();
    }
}

更多详情可以通过here

【讨论】:

    猜你喜欢
    • 2020-07-03
    • 2017-05-20
    • 2019-03-23
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 2013-07-24
    • 2018-12-01
    • 2019-12-14
    相关资源
    最近更新 更多