我正在阅读几个资源(书籍和SO答案)关于WebApi中的授权。
假设我想添加自定义属性,仅允许特定用户访问:
情况#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);
}
}
}
案例 #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
是否已设置。如果未设置,则表示请求已获得授权且用户已通过验证。
情况#3
但我也看到了覆盖IsAuthorized
的这种方法:
public class AllowOnlyCertainUsers : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext context)
{
if ( /*check if user OK or not*/)
{
return true;// or false
}
}
}
案例 #4
然后我看到了一个类似的例子,但是通过调用base.IsAuthorized(context):
protected override bool IsAuthorized(HttpActionContext context)
{
if (something1 && something2 && base.IsAuthorized(context)) //??
return true;
return false;
}
还有一件事
最后,Dominick在这里说:
你不应该重写OnAuthorization - 因为你会错过[AllowAnonymous]处理。
问题
1)我应该使用哪些方法:
IsAuthorized
或OnAuthorization
?(或者何时使用哪个)2)何时调用
base.IsAuthorized
或base.OnAuthorization
?3)他们是这样构建的吗?如果响应为空,则一切正常吗?(情况#2)
NB
请注意,我仅使用(并希望使用)AuthorizeAttribute
,它已经继承了AuthorizationFilterAttribute
为什么?
因为我处于第一阶段:http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api
无论如何,我是通过扩展Authorize属性来提问的。