您好,我想在我的控制器中的操作方法上放置一個授權過濾器,可以由同一用戶或其他管理員訪問。ASP.NET MVC 4授權給同一用戶或其他管理員
假設有一個用戶Alex註冊我的網站,現在想編輯他的個人資料。所以他應該被允許編輯他的個人資料而不是其他人,或者管理員將有權編輯每個人的個人資料。
我可以在Authorize屬性中添加角色admin,但是如何解決自我用戶的問題。好心幫
[Authorize(Roles="admin")]
您好,我想在我的控制器中的操作方法上放置一個授權過濾器,可以由同一用戶或其他管理員訪問。ASP.NET MVC 4授權給同一用戶或其他管理員
假設有一個用戶Alex註冊我的網站,現在想編輯他的個人資料。所以他應該被允許編輯他的個人資料而不是其他人,或者管理員將有權編輯每個人的個人資料。
我可以在Authorize屬性中添加角色admin,但是如何解決自我用戶的問題。好心幫
[Authorize(Roles="admin")]
這是一個授權過濾器的一個例子,將檢查用戶名(也可以GUID或任何其他方式)傳遞路線和檢查用戶角色的管理員
的參數相匹配public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (!httpContext.User.Identity.IsAuthenticated)
return false; // if user not Authenticated, do not allow
string userName = filterContext.HttpContext.User.Identity.Name;
string id = filterContext.RouteData.Values[this.RouteParameter];
If (userName == id)
return true; // assuming paramter passed matches username, allow
else if (filterContext.HttpContext.User.IsInRole("Admin") || IsOwner(filterContext))
return true; // if user has role Admin, allow
return true;
}
}
雖然這是未經測試的,並且意在引導更多的解決您的需求,但我認爲它將接近實施。
同時,我想補充我的2美分,你的方法:
我贊成行爲過濾器,會做類似的檢查,將用戶重定向到自己的網頁或警告的是更多頁。雖然我很看重安全授權過濾器提供的功能,但我發現它們很生硬。我更喜歡基於權限的安全性和軟重定向,以提供更優雅的用戶體驗。
這就是我如何在我的更改密碼中進行操作,以便只有該用戶才能更改他/她自己的密碼。
在我帳戶控制
//
// GET: /Account/ChangePassword
[Authorize]
public ActionResult ChangePassword()
{
return View();
}
//
// POST: /Account/ChangePassword
[Authorize]
[HttpPost]
public ActionResult ChangePassword(ChangePasswordModel model)
{
if (ModelState.IsValid)
{
if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
return RedirectToAction("ChangePasswordSuccess");
else
ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
}
// If we got this far, something failed, redisplay form
return View(model);
}
然後在我_layout我宣佈它像這樣使得只有用戶可以看到並打開ActionLink的和改變他/她自己的密碼
@if (HttpContext.Current.User.Identity.IsAuthenticated)
{
<li>@Html.ActionLink("Change Password", "ChangePassword", "Account")</li>
}
希望這也能幫助你..乾杯。 :)
這看起來不錯,將執行此 – 1Mayur 2013-02-25 12:32:36
@Dave Alperovich你從哪裏得到'filterContext'和'IsOwner'? – 2015-10-25 13:58:51