Web.API中的自定义授权

我对ASP.NET MVC的理解是,对于授权,我应该使用类似的东西 –

public class IPAuthorize : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { //figure out if the ip is authorized //and return true or false } 

但在Web API中,没有AuthorizeCore(..)

OnAuthorization(..) ,MVC的一般建议是不使用OnAuthorization(..)

我应该在Web API中使用什么来进行自定义授权?

我根本不同意对立面 –

授权在授权filter中完成 – 这意味着您从System.Web.Http.AuthorizeAttribute派生并实现IsAuthorized方法。

您没有在普通的操作filter中实现授权,因为它们在管道中的运行时间晚于授权filter。

您也不会在filter中实现身份validation(如解析JWT) – 这在名为MessageHandler的可扩展性点中甚至更早完成。

我们使用的方法是一个inheritance自System.Web.Http.AuthorizeAttribute的自定义ApiAuthorize属性。 例如:

 public class ApiAuthorizeAttribute : AuthorizeAttribute { readonly CreditPointModelContext _ctx = new CreditPointModelContext(); 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 { //boolean logic to determine if you are authorized. //We check for a valid token in the request header or cookie. } catch (Exception) { return false; } } }