如果
,我希望锁定对用户编辑页面的访问权限(例如/user/pure.krome/edit)a)Identity.IsAuthenticated = false
或者他们已通过身份验证,但
b)Idenitity.Name!=他们试图编辑的用户页面的用户名
c)Identity.UserType()!= UserType.Administrator //这就像一个角色,不使用RoleProviders。
我假设你可以用某些东西来装饰控制器或控制器的动作方法,但我只是不确定是什么?
答案 0 :(得分:3)
查看AuthorizeAttribute
。
答案 1 :(得分:3)
从AuthorizeAttribute派生的自定义属性就是我用来做这件事的。覆盖OnAuthorize方法并实现自己的逻辑。
public class OnlyUserAuthorizedAttribute : AuthorizeAttribute
{
public override void OnAuthorize( AuthorizationContext filterContext )
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new HttpUnauthorizeResult();
}
...
}
}
答案 2 :(得分:2)
我实现了以下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
}