ASP.NET身份验证POST策略

时间:2019-01-18 10:17:42

标签: asp.net

我目前正在使用POST控制器。过去,我曾在控制器本身中处理过有关身份验证的逻辑,

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

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

是否可以制作一个[Policy =(“ fooPoster”)]并可以使用其中的帖子正文来确定我是否被授权访问该帖子,或者我只能访问全局状态来确定它?

1 个答案:

答案 0 :(得分:0)

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

    [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

相关问题