本文共 1572 字,大约阅读时间需要 5 分钟。
如何实现基于角色的权限控制
[Authorize(Roles = "admin")] 标记的action只能是认证用户才能访问。 FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
userName,
DateTime.Now,
DateTime.Now.AddMinutes(20),
false,
"admin"//写入用户角色
);
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
[Authorize(Roles =
"admin")]
标记的action只能是认证用户才能访问。
FormsAuthenticationTicket authTicket =
new FormsAuthenticationTicket(
1,
userName,
DateTime.Now,
DateTime.Now.AddMinutes(20),
false,
"admin" //写入用户角色 );
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
System.Web.HttpCookie authCookie =
new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie ==
null || authCookie.Value == "")
{
return;
}
FormsAuthenticationTicket authTicket =
null;
try {
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch {
return;
}
string[] roles = authTicket.UserData.Split(
new char[] { ';' });
if (Context.User !=
null)
{
Context.User =
new System.Security.Principal.GenericPrincipal(Context.User.Identity, roles);
}
}
ok,这样就可以实现角色权限的控制
本文转自 BruceAndLee 51CTO博客,原文链接:http://blog.51cto.com/leelei/317919,如需转载请自行联系原作者