我創建ASP.NET MVC應用程序,這是我的問題:何處實施額外的授權業務邏輯?
當accesing在控制器的動作,如果在與授權屬性所允許的角色登錄用戶檢查身邊,我需要包括邏輯,如果conserning用戶i希望編輯(它的ID來作爲行動參數)比登錄用戶低的角色(我不希望允許普通用戶編輯管理員等)
我應該在哪裏實施這個邏輯是什麼?我想覆蓋AuthorizeAttribute方法和簡單地添加這個邏輯存在,但在這種情況下,我不得不送我希望在屬性的參數編輯的用戶,但是這是不允許的。
另一種選擇是在控制器中創建私有方法,但如果我想使用其他控制器這個邏輯我將不得不一次又一次地重複這種代碼。
什麼是正確的解決方案嗎?
[AttributeUsageAttribute(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeRolesAttribute : AuthorizeAttribute
{
private string _roles { get; set; }
private UserEntity _user { get; set; }
private UserEntity _loggedUser { get; set; }
public AuthorizeRolesAttribute(string Roles, string User, int Id)
{
_user = new UserEntity();
_loggedUser = new UserEntity();
_roles = Roles;
}
//Called when access is denied
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(new { controller = "Account", action = "LogOn" })
);
}
//Core authentication, called before each action
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool b = false;
string[] roles = _roles.Split(',');
//Is user logged in?
if (httpContext.User.Identity.IsAuthenticated)
{
//If user is logged in and we need a custom check:
if (roles.Any(r => httpContext.User.IsInRole(r)) && HasPermission(_user, _loggedUser))
b = true;
}
//Returns true or false, meaning allow or deny. False will call HandleUnauthorizedRequest above
return b;
}
private bool HasPermission(UserEntity user, UserEntity loggedUser)
{
if (user.IsAdmin) return false;
if (loggedUser.IsAdmin || loggedUser.IsApplicationAdmin) return true;
if (loggedUser.IsAmbassador)
{
if (user.IsApplicationAdmin)
{ return false; }
else
{ return true; }
}
return false;
}
}
正如你所看到的,此刻我只是創建空的虛假對象 _user和 _loggedUser在構造函數中,因爲我不知道如何通過他們。
我知道我應該實現這些,我已經做到了。但我需要傳遞一個用戶對象,讓我們說UserEntity類。我知道我不能這樣做,所以至少我想遞給我的用戶唯一的用戶電子郵件。當我實現我的自定義屬性的權利,我可以做這樣的事情嗎? [CustomAttribute(角色=「管理員,管理員」),電子郵件= Model.UserToEdit] ...我敢肯定,我不能,我只能硬編碼像電子郵件= [email protected] ...但我不知道是什麼電子郵件應該在那個時候 – Martin 2014-10-30 10:17:14