如何在ASP.NET Core中创建自定义Authorize属性?

时间:2017-04-30 13:45:24

标签: c# asp.net asp.net-core asp.net-core-mvc .net-core

在MVC 4中,我们可以覆盖AuthorizeAttribute类的一些方法来实现自定义Authorize属性。

例如:https://stackoverflow.com/a/21634723/6120338

public class DemoAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        if (Authorize(actionContext))
        {
            return;
        }
        HandleUnauthorizedRequest(actionContext);
    }

    protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        var challengeMessage = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
        challengeMessage.Headers.Add("WWW-Authenticate", "Basic");
        throw new HttpResponseException(challengeMessage);
    }

    private bool Authorize(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        try
        {
            var someCode = (from h in actionContext.Request.Headers where h.Key == "demo" select h.Value.First()).FirstOrDefault();
            return someCode == "myCode";
        }
        catch (Exception)
        {
            return false;
        }
    }
}

和控制器将

[DemoAuthorize]
public class ValuesController : ApiController{

这是在MVC4中。但是如何在ASP.NET CORE中做同样的事情呢?
OnAuthorization类中没有HandleUnauthorizedRequestAuthorizeAuthorizeAttribute重写方法。

0 个答案:

没有答案