我希望锁定对用户的EDIT页面的访问权限(例如/user/pure.krome/edit)
a)Identity.IsAuthenticated = false
或者他们经过身份验证但是
b)Idenitity.Name!=他们试图编辑的用户页面的用户名 c)Identity.UserType()!= UserType.Administrator //这就像一个角色,不使用RoleProviders。
我假设你可以用某些东西装饰一个控制器或一个控制器的动作方法,但我只是不确定是什么?
看看AuthorizeAttribute
。
从AuthorizeAttribute派生的自定义属性就是我用来做这件事的。覆盖OnAuthorize方法并实现自己的逻辑。
public class OnlyUserAuthorizedAttribute : AuthorizeAttribute
{
public override void OnAuthorize( AuthorizationContext filterContext )
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new HttpUnauthorizeResult();
}
...
}
}
我实现了以下ActionFilterAttribute,它可以处理身份验证和角色。我将角色存储在我自己的数据库表中,如下所示:
public class CheckRoleAttribute : ActionFilterAttribute
{
public string[] AllowedRoles { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string userName = filterContext.HttpContext.User.Identity.Name;
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
if (AllowedRoles.Count() > 0)
{
IUserRepository userRepository = new UserRepository();
User user = userRepository.GetUser(userName);
bool userAuthorized = false;
foreach (Role userRole in user.Roles)
{
userAuthorized = false;
foreach (string allowedRole in AllowedRoles)
{
if (userRole.Name == allowedRole)
{
userAuthorized = true;
break;
}
}
}
if (userAuthorized == false)
{
filterContext.HttpContext.Response.Redirect("/Account/AccessViolation", true);
}
}
else
{
filterContext.HttpContext.Response.Redirect("/Account/AccessViolation", true);
}
}
else
{
filterContext.HttpContext.Response.Redirect(FormsAuthentication.LoginUrl + String.Format("?ReturnUrl={0}", filterContext.HttpContext.Request.Url.AbsolutePath), true);
}
}
我称之为......
[CheckRole(AllowedRoles = new string[] { "admin" })]
public ActionResult Delete(int id)
{
//delete logic here
}