我正在閱讀有關WebApi授權的一些資源(書籍和SO答案)。Asp.net 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(上下文):
protected override bool IsAuthorized(HttpActionContext context)
{
if (something1 && something2 && base.IsAuthorized(context)) //??
return true;
return false;
}
一件事
最後多米尼克說here:
你不應該重寫OnAuthorization - 因爲你會錯過[使用AllowAnonymous]處理。
問題
1)我應該使用哪種方法:
IsAuthorized
或OnAuthorization
? (或何時使用)2)什麼時候應該撥打
base.IsAuthorized or
base.OnAuthorization`?3)他們是如何構建它的?如果響應是空的,那麼一切都好?(案例#2)
NB
請注意,我使用(並希望使用)僅AuthorizeAttribute
它已經從AuthorizationFilterAttribute
爲什麼繼承?
監守我在第一階段中:http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api
反正林通過延長授權的屬性要求。
你需要重寫Authorize屬性嗎?你想達到什麼樣的用例?如果您需要允許某些用戶訪問,爲什麼不使用這樣的[Authorize(Users =「Admin」)]屬性? – 2014-10-20 13:08:44
@TaiseerJoudeh例如,嘗試在10:00至12:00之間授權用戶(可配置)。你不能用簡單的角色和授權的attr來做到這一點。你必須制定你自己的邏輯 – 2014-10-20 13:11:21