[英]Custom authorization in Razor view
我目前正在從事C#MVC項目。 我使用CustomAuthorizationAttribute
來授權項目中的每個用戶。
我有3個角色:超級管理員,管理員和用戶
創建新用戶時,可以選擇添加相應的角色,並且可以對其進行編輯(具有“用戶”角色的人不能添加或編輯用戶)。
為了設置此身份驗證,我分別創建了兩個表“ PermissionFunction ”和“ Permission ”。 該表的詳細信息如下:
PermissionFunction :
|---------------------|------------------|
| PermFunc_ID | bigint |
|---------------------|------------------|
| PermFunc_Name | varchar(50) |
|---------------------|------------------|
權限 :
|---------------------|------------------|
| Perm_ID | bigint |
|---------------------|------------------|
| Perm_RollID | bigint |
|---------------------|------------------|
| Perm_PermFuncID | bigint |
|---------------------|------------------|
PermFunc_ID和Perm_ID分別是表的主鍵。 PermFunc_Name是引用所有控制器中每個動作的名稱。 權限表包含Role和PermissionFunction表的外鍵。
供參考的是我的角色表:
|---------------------|------------------|
| Rol_ID | bigint |
|---------------------|------------------|
| Rol_Name | varchar(50) |
|---------------------|------------------|
為了進行身份驗證,我添加了一個類CustomAuthorizationAttribute並將授權屬性添加到每個控制器操作中。
例如,考慮我的PermissionFunction表值,如下所示:
|---------------------|-------------------|
| PermFunc_ID | PermFunc_Name |
|---------------------|-------------------|
| 1 | userIndex |
|---------------------|-------------------|
| 2 | userCreate |
|---------------------|-------------------|
和我的HomeController :
public class UserController : Controller
{
[CustomAuthorization(IdentityRoles = "userIndex")]
public ActionResult Index()
{
return View();
}
[CustomAuthorization(IdentityRoles = "userCreate")]
public ActionResult Create()
{
return View();
}
}
和CustomAuthorizationAttribute類:
public class CustomAuthorizationAttribute : AuthorizeAttribute
{
private PermissionRepository _permission = new PermissionRepository();
private PermissionFuncRepository _permissionFun = new PermissionFuncRepository();
// roles start
public string IdentityRoles
{
get { return _permissionName ?? String.Empty; }
set { _permissionName = value; }
}
private string _permissionName;
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
//do the base class AuthorizeCore first
if (httpContext.User.Identity.IsAuthenticated)
{
string RoleID = FormsAuthentication.Decrypt(httpContext.Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name.Split('|')[1];
var permisionID = _permissionFun.FindByName(_permissionName);
if(permisionID != null)
{
var permis = _permission.GetPermission().Where(a => a.Perm_PermFuncID == permisionID.PermFunc_ID && a.Perm_RollID.ToString() == RoleID).FirstOrDefault();
if (permis != null)
{
return true;
}
}
}
return false;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
//if the user is not logged in use the deafult HandleUnauthorizedRequest and redirect to the login page
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
base.HandleUnauthorizedRequest(filterContext);
}
//if the user is logged in but is trying to access a page he/she doesn't have the right for show the access denied page
else
{
// the controller action was invoked with an AJAX request
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new RedirectResult("~/Home/AccessDeniedNew");
}
else
{
filterContext.Result = new RedirectResult("~/Home/AccessDenied");
}
}
}
}
一切正常。
這是我的索引 html:
<button class="btn btn-sm btn-rounded btn-success" type="button" id ="CreateButton" onclick="UserCreate()"> Create New User </button> // create new user ..... // code continues // code for modal popup <div id="edit-user" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> </div> <script type="text/javascript"> function UserCreate() { var url = "/User/Create/"; $.get(url, function (data) { $('#edit-user').html(data); $('#edit-user').modal('show'); }); } </script>
單擊CreateButton時 ,將彈出一個模態彈出窗口,用於添加詳細信息並創建新用戶。
如果用戶無權創建新用戶,有什么辦法可以隱藏“創建新”按鈕? (即:如果userCreate不在PermissionFunction表中)。
您可以檢查權限,並在需要時向頁面添加按鈕。 您已經知道獲取權限信息的方法,因此可以將一些信息存儲在ViewData
或ViewBag
並檢查是否應存在創建按鈕。 該信息可以只是一個簡單的boolean
。 會是這樣的
@if(ViewBag.CanCreate)
{
<button class="btn btn-sm btn-rounded btn-success" type="button" id ="CreateButton" onclick="UserCreate()"> Create New User </button>
}
您可以在控制器上設置CanCreate
。
我寧願建議你從這個話題
但是解決方案不是很好,您可以創建自己的操作鏈接,例如
@html.AuthorizeActionLink("button name","your action/controller name","your security role")
我認為您甚至可以擺脫最后一個參數,並自動檢查連接的用戶以及您要選擇顯示或不顯示的操作所要求的權限。
如果您確實需要特定的html,那么我建議在此線程中使用解決方案。如果您要在一頁上處理多個訪問權限,則會更容易。 確實,如果您要管理許多Viewbag,將開始感到痛苦。
希望這可以幫助
問候
編輯:對於FPGA實現的authorizeActionLink我發現這
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.