ASP.NET MVC 4授权给同一用户或其他管理员
问题描述:
您好,我想在我的控制器中的操作方法上放置一个授权过滤器,可以由同一用户或其他管理员访问。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