在VS 2003中:
1、以用户名为条件将用户所属的角色从数据库中查询出来,方法为自己写SQL语句。
2、生成用户验证票据,将用户角色加入票据,如下面的result就为用户角色字符串,
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // Ticket version
usrname.Text.Trim(), // Username associated with ticket
DateTime.Now, // Date/time issued
DateTime.Now.AddMinutes(30), // Date/time to expire
true, // "true" for a persistent user cookie
result, // User-data, in this case the roles
FormsAuthentication.FormsCookiePath); // Path cookie valid for
// Encrypt the cookie using the machine key for secure transport
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName, // Name of auth cookie
hash); // Hashed ticket
// Set the cookie's expiration time to the tickets expiration time
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
// Add the cookie to the list for outgoing response
Response.Cookies.Add(cookie);
3、在Global.asax中加入
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 id =
(FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
// Get the stored user-data, in this case, our roles
string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new GenericPrincipal(id, roles);
}
}
}
}
4、判断某个用户是不是属于指定的角色,用如下的方法,
User.IsInRole("角色名称");
在VS 2005中,由于有了一系列Login控件,方便多了:
1、以用户名为条件将用户所属的角色找出来,用如下的方法
string[] roles = Roles.GetRolesForUser(userName);
2、生成用户票据,用如下方法,其中roles为用户角色数组
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
userName,
DateTime.Now,
DateTime.Now.AddMinutes(60),
isPersistent,
roles.Length == 0 ? String.Empty : String.Join("|", roles),
FormsAuthentication.FormsCookiePath);
// Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(ticket);
HttpResponse response = null;
if (HttpContext.Current != null)
{
response = HttpContext.Current.Response;
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName,
encTicket);
// Create the cookie.
response.Cookies.Add(cookie);
}
3、判断某个用户是不是属于指定的角色,用如下的方法,
Roles.IsUserInRole("用户名称", "角色名称");