我正在阅读有关 Web Api 授权的多个资源(书籍和一些答案)。
假设我想添加仅允许某些用户访问的自定义属性:
Case #1
我见过这种方法压倒性的 OnAuthorization
,如果出现问题,它会设置响应
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)
{
//...
}
}
然后,您检查是否HttpActionContext.Response
是否设置。如果不设置,则表示请求已授权,用户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
然后我看到了类似的示例一,但调用了 base.IsAuthorized(context) :
protected override bool IsAuthorized(HttpActionContext context)
{
if (something1 && something2 && base.IsAuthorized(context)) //??
return true;
return false;
}
还有一件事
最后多米尼克说here :
您不应该覆盖 OnAuthorization - 因为您将缺少 [AllowAnonymous] 处理。
问题
1)我应该使用哪些方法:IsAuthorized
or OnAuthorization
? (或何时使用哪个)
2)我什么时候应该打电话base.IsAuthorized or
基础.OnAuthorization` ?
3)他们就是这样建造的吗?如果响应为空那么一切都好? (案例#2)
NB
请注意,我仅使用(并且想要使用)AuthorizeAttribute
它已经继承自AuthorizationFilterAttribute
Why ?
因为我正处于第一阶段:http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api
无论如何,我通过扩展 Authorize 属性来询问。