I'm reading from several resources (books and SO answers) about authorization in WebApi.
假设我想添加只允许某些用户访问的自定义属性:
Case #1
我见过overridingOnAuthorization
这种方法,如果出现问题,它会设置响应
public class AllowOnlyCertainUsers : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if ( /*check if user OK or not*/)
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
}
}
Case #2
但我也见过这个类似的例子,它也超过了OnAuthorization
,但呼叫到了base
:
public override void OnAuthorization(HttpActionContext actionContext)
{
base.OnAuthorization(actionContext);
// If not authorized at all, don't bother
if (actionContext.Response == null)
{
//...
}
}
Then, you check if the 100 is set or not. If it’s not set, it means that the request is authorized and the user is ok
Case #3
但我也见过这种超越IsAuthorized
的方法:
public class AllowOnlyCertainUsers : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext context)
{
if ( /*check if user OK or not*/)
{
return true;// or false
}
}
}
Case #4
然后我看到了一个类似的例子,不过是呼叫基地.未授权(上下文):
protected override bool IsAuthorized(HttpActionContext context)
{
if (something1 && something2 && base.IsAuthorized(context)) //??
return true;
return false;
}
One more thing
最后多米尼克说here:
You shouldn't override OnAuthorization - because you would be missing [AllowAnonymous] handling.
Questions
1) 我应该使用哪些方法:
IsAuthorized
还是OnAuthorization
?(或何时使用哪个)2)何时拨打
base.IsAuthorized or
base.OnAuthorization`?3)他们是这样建造的吗?如果响应为空,则一切正常?( case 2)
注意事项
请注意,我只使用了(并且希望使用)从AuthorizationFilterAttribute
继承的AuthorizeAttribute
为什么?
因为我在第一阶段:http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api
不管怎样,我是通过扩展授权属性来询问的.