C# Web.API 中的自定义授权
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15148050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Custom authorizations in Web.API
提问by tom
My understanding of ASP.NET MVC is that for authorizations I should use something like -
我对 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
}
But in Web API, there is no AuthorizeCore(..)
.
但是在 Web API 中,没有AuthorizeCore(..)
.
There is OnAuthorization(..)
and the general advice for MVC is not to use OnAuthorization(..)
.
有OnAuthorization(..)
和MVC一般的建议是不要使用OnAuthorization(..)
。
What should I use for custom authorizations in Web API?
Web API 中的自定义授权应该使用什么?
采纳答案by leastprivilege
Authorization is done in an authorization filter - that mean you derive from System.Web.Http.AuthorizeAttribute and implement the IsAuthorized method.
授权在授权过滤器中完成 - 这意味着您从 System.Web.Http.AuthorizeAttribute 派生并实现 IsAuthorized 方法。
You don't implement authorization in a normal action filter because they run later in the pipeline than authorization filters.
您不会在普通操作过滤器中实现授权,因为它们在管道中的运行时间晚于授权过滤器。
You also don't implement authentication in a filter (like parsing a JWT) - this is done even earlier in an extensibility point called MessageHandler.
您也不会在过滤器中实现身份验证(如解析 JWT) - 这甚至在名为 MessageHandler 的可扩展点中更早完成。
回答by Gareth Suarez
The method we use for is an custom ApiAuthorize attribute that inherits from System.Web.Http.AuthorizeAttribute. for example:
我们使用的方法是从 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;
}
}
}