public static void SetLoginCookie(AdminUserVO u, string roles)
{
//建立身份验证票对象
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,u.Uname, DateTime.Now, DateTime.Now.AddMinutes(30), false,roles,"/");
//加密序列化验证票为字符串
string hashTicket = FormsAuthentication.Encrypt (ticket) ;
HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
HttpContext.Current.Response.Cookies.Add(userCookie);
}
FormsAuthenticationTicket参数说明:
FormsAuthenticationTicket(
int version, //设为1,版本号由系统自动提供
string name, //用户标示,获取与身份验证 Cookie 关联的用户名
DateTime issueDate, //Cookie 的发出时间, 设置为 DateTime.Now
DateTime expiration, //获取 Cookie 过期的日期/时间
bool isPersistent, //是否持久性(根据需要设置,若是设置为持久性,在发出cookie时,cookie的Expires设置一定要设置),如果已发出持久的 Cookie,则返回 true。否则,身份验证 Cookie 将限制在浏览器生命周期范围内。
string userData, //获取存储在 Cookie 中的应用程序定义字符串,这里用上面准备好的用逗号分割的role字符串
string cookiePath // 返回发出 Cookie 的路径。注意,窗体的路径设置为"/",这要同发出cookie的路径一致,因为刷新cookie要用这个路径。由于窗体区分大小写,这是为了防止站点中的 URL 的大小写不一致而采取的一种保护措施。
);
2.Global.asax.cs加入下面的方法
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if(HttpContext.Current.User!=null)
{
if(HttpContext.Current.User.Identity.IsAuthenticated)
{
if(HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity fi = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = fi.Ticket;
string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new GenericPrincipal(fi,roles);
}
}
}
}
一个基于角色认证的英文资料Role-based Security with Forms Authentication