[英]Custom authorise attribute not overriding/combining on specific actions
我創建了一個自定義授權屬性,以允許進行一些自定義檢查來確定對整個應用程序的訪問。
當在控制器級別應用自定義auth屬性,然后嘗試添加對特定操作的其他訪問權限時,角色將不會以“添加”方式應用。
自定義授權屬性:
// Allow multiple = true so should roll all occurrences in a request into one
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class CustomAuthoriseAttribute : AuthorizeAttribute
{
public CustomAuthoriseAttribute(params string[] roles)
{
this.Roles = string.Join(",", roles);
}
/// <summary>
/// Custom routines to determine if a request is considered authorised.
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
var userManager = httpContext.GetOwinContext().GetUserManager<UserManager>();
var user = userManager.FindById(httpContext.User.Identity.GetUserId());
if (user == null)
{
return false;
}
// Log the user out as they should not be allowed access
if (user.IsDisabled || user.IsDeleted)
{
httpContext.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
httpContext.Session.Clear();
return false;
}
return base.AuthorizeCore(httpContext);
}
}
控制器中的用法:
似乎要對SuperAdmin和Admin進行auth檢查,然后再對Consultant進行檢查,這會導致未經授權的請求。 為什么不完全對他們進行治療?
[CustomAuthorise(SuperAdministrator, Administrator)]
public class SomeController : Controller
{
public const string SuperAdministrator = "SuperAdministrator";
public const string Administrator = "Administrator";
public const string Consultant = "Consultant";
// Should only accessible by SuperAdministrators and Administrators
[HttpGet]
public ActionResult Index()
{
return View();
}
// Should be accessible by SuperAdministrators, Administrators and Consultants
[HttpGet]
[CustomAuthorise(Consultant)]
public ActionResult SomeAction()
{
return View();
}
}
多個授權屬性使用邏輯與進行處理。 每個屬性的結果與前一個屬性進行“與”運算。 在這種情況下,只有超級管理員或管理員(基於控制器級別屬性)並且他們是顧問(基於操作級別屬性)的人員才能訪問SomeAction。
有幾種不同的方法來執行此操作,但是我建議不要在控制器級別授予顧問訪問權限,因為您將特權帳戶(超級管理員和管理員)與受限帳戶(顧問)混合在一起。
我將創建一個可被所有三個角色訪問的新控制器,並將此動作移到那里。 然后,您可以將特權方法留在原始控制器中。
[CustomAuthorise(SuperAdministrator, Administrator)]
public class PrivilegedController : Controller
{
// Should only accessible by SuperAdministrators and Administrators
[HttpGet]
public ActionResult Index()
{
return View();
}
}
[CustomAuthorise(SuperAdministrator, Administrator, Consultant)]
public class LessPrivilegedController : Controller
{
[HttpGet]
public ActionResult SomeAction()
{
return View();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.