您的位置:首页 > 编程语言 > ASP

asp.net mvc 中,抛弃membership结合自定义的权限表来使用[Authorize]

2012-01-10 20:16 477 查看
asp.net mvc 中使用[Authorize]属性,必须要开启角色管理,同时还要使用membership。这对于自定义的权限系统来说,有种“鱼和熊掌不能兼得”的感觉,但可以通过使用FormsAuthenticationTicket,将角色信息添加到cookies中,然后将cookies读出来,获得角色信息添加到HttpContext.User中,这样当使用[Authorize]属性时,就会得到角色信息。实际上网上有这样的文章,只是没有关于这样的说明。

另外还有人提出这样的方法:继承AuthorizeAttribute,override AuthorizeCore方法。

以下代码来自网络:

MVC2中Authorize中的代码(AuthorizeAttribute.cs)是这样的:

// This method must be thread-safe since it is called by the thread-safe OnCacheAuthorization() method.
protected virtual bool AuthorizeCore(HttpContextBase httpContext) {
if (httpContext == null) {
throw new ArgumentNullException("httpContext");
}

IPrincipal user = httpContext.User;
if (!user.Identity.IsAuthenticated) {
return false;
}

if (_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) {
return false;
}

if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole)) {
return false;
}

return true;
}

根据代码,修改httpContext.User的信息。

1。修改Global.asax

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
FormsAuthenticationTicket authTicket = null;
if (authCookie!=null)
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
string[] roles = authTicket.UserData.Split(new char[] { ',' });//如果存取多个角色,我们把它分解
FormsIdentity id = new FormsIdentity(authTicket);
GenericPrincipal principal = new GenericPrincipal(id, roles);
Context.User = principal;//存到HttpContext.User中
}


2。在MODEL的signIn的方法中添加下列代码:

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, userName, DateTime.Now, DateTime.Now.AddMinutes(60), false, "Admin,Test");
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName,encryptedTicket);
HttpContext.Current.Response.Cookies.Add(authCookie);

代码很简单,具体内容不解释 。此文仅仅作为个人的一个工作日志。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: