我有以下要求来实现访问控制列表
public class SecurityObject{
public string Key{get;set;}
public string DisplayName{get;set;}
public bool isAllowed{get;set;}
}
public class Role{
List<SecurityObject> AccessibleObjects{get;set;}
}
目前,我使用表单身份验证进行基本授权。以下是我的代码
的Global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
public override void Init()
{
this.PostAuthenticateRequest += new
EventHandler(MvcApplication_PostAuthenticateRequest);
base.Init();
}
void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
HttpCookie authCookie =
HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
string encTicket = authCookie.Value;
if (!String.IsNullOrEmpty(encTicket))
{
FormsAuthenticationTicket ticket =
FormsAuthentication.Decrypt(encTicket);
string[] userData = ticket.UserData.Split(new string[] { "___" },
StringSplitOptions.None);
string[] roles = null;
if (userData.Length > 1)
{
roles = userData[1].Split(',');
}
MyCustomIdentity identity = new MyCustomIdentity(ticket);
GenericPrincipal principle = new GenericPrincipal(identity, roles);
HttpContext.Current.User = principle;
}
}
}}
我当前的控制器类
public class AdminController : Controller
{
[HttpPost, Authorize, ValidateAntiForgeryToken]
public ActionResult SaveUser(UserDetailViewModel viewModel)
{
}
}
我的目标控制器类
public class AdminController : Controller
{
[HttpPost, Authorize(ACLKey="USR_SAVE"), ValidateAntiForgeryToken]
public ActionResult SaveUser(UserDetailViewModel viewModel)
{
}
}
我希望我的action方法用ACLKey修饰,我想检查用户角色是否具有给定的密钥,并根据我需要执行或返回HttpUnauthorizedResult页面,即使是来自jQuery的Ajax请求。
我提到了许多像Customizing authorization in ASP.NET MVC但我找不到执行表单身份验证和自定义ACLKey检查的方法。
如何解析值USR_SAVE
并使用 CustomAuthorizeFilter处理自定义身份验证?
答案 0 :(得分:5)
您可以尝试这样
public class FeatureAuthenticationAttribute : FilterAttribute, IAuthorizationFilter
{
public string AllowFeature { get; set; }
public void OnAuthorization(AuthorizationContext filterContext)
{
var filterAttribute = filterContext.ActionDescriptor.GetFilterAttributes(true)
.Where(a => a.GetType() ==
typeof(FeatureAuthenticationAttribute));
if (filterAttribute != null)
{
foreach (FeatureAuthenticationAttribute attr in filterAttribute)
{
AllowFeature = attr.AllowFeature;
}
List<Role> roles =
((User)filterContext.HttpContext.Session["CurrentUser"]).Roles;
bool allowed = SecurityHelper.IsAccessible(AllowFeature, roles);
if (!allowed)
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
}
}
在你的行动方法
[FeatureAuthentication(AllowFeature="USR_SAVE")]
public ActionResult Index()
{
}
希望这会对你有帮助!
答案 1 :(得分:1)
您可以使用过滤器属性:
public class ACLCheckAttribute : FilterAttribute, IActionFilter
在OnActionExecuting中,您可以获取USR_SAVE。不知道它来自何处,我认为它来自:
如果在其他地方,请在哪里评论。您可以将此属性应用于控制器或方法,也可以通过将其添加到globalfilters集合(GlobalFilters.Filters.Add())或App_Start文件夹中的FilterConfig文件进行全局设置。