[英]MVC Custom Authorize Attribute From Database
我在數據庫中創建了自己的自定義角色表,並且還希望創建一個自定義授權屬性。
到目前為止,這是我所擁有的,但是我不確定如何進行:
private List<RoleModel> Roles;
private IRoleRepository repo;
private ICustomerRepository cust;
public bool CheckRoles(string UserId)
{
try
{
Roles = repo.GetAll().ToList();
CustomerModel Customer = cust.Get(UserId);
int CustomerRole = Customer.RoleId;
RoleModel role = Roles.First(x => x.id == CustomerRole);
}
catch(Exception e)
{
return false;
}
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
string UserId = filterContext.HttpContext.User.Identity.GetUserId();
}
如果有人可以幫助我完成這項工作,我將不勝感激。
謝謝!
我認為創建自定義AuthorizeAttribute不是一個好主意。 最好使用標准AuthorizeAttribute。
擁有自己的角色表是一種常見的情況。 最好重寫如何設置主體身份的角色並使用AuthorizeAttribute的Roles屬性。 用戶登錄時,將角色設置為聲明。 它將比在每次請求時從自定義Authorize屬性中的數據庫檢索角色更好。 設置您的CalimTypes.Role聲明,然后使用以下命令保護您的控制器/動作:
[Authorize(Roles = "admin")]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.