asp.net form验证
匿名用户不可以登陆
<authentication mode="Forms">
<forms loginUrl="login.aspx" name=".ASPXFORMSAUTH" defaultUrl="default.aspx"></forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
发动验证凭证
string roleString = role;// +"," + group;
System.Web.Security.FormsAuthenticationTicket ticket
= new FormsAuthenticationTicket(2, userName, DateTime.Now, DateTime.Now.AddDays(3), true, roleString);
string cookieString = System.Web.Security.FormsAuthentication.Encrypt(ticket);
// 保存到 Cookie
HttpCookie cookie = new HttpCookie(
System.Web.Security.FormsAuthentication.FormsCookieName);
cookie.Value = cookieString;
this.Response.Cookies.Add(cookie);
if (Request.QueryString["returnurl"] != null)
{
string returnurl = Request.QueryString["returnurl"];
Response.Redirect(returnurl);
}
else
{
Response.Redirect("default.aspx");
}
解析用户角色
void Application_PostAuthenticateRequest(object sender, EventArgs e)
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
if (context.User.Identity.IsAuthenticated)
{
// 取得用户对象
System.Security.Principal.IPrincipal user = context.User;
// 取得用户的角色数组
System.Web.Security.FormsIdentity fi = user.Identity as System.Web.Security.FormsIdentity;
// 取得用户的票据
System.Web.Security.FormsAuthenticationTicket ticket = fi.Ticket;
// 创建用户所拥有的角色数组
string roleString = ticket.UserData;
// 还原为字符串数组
string[] roleArray = { roleString };//roleString.Split(',');
// 自己创建用户对象
System.Security.Principal.GenericPrincipal principal
= new System.Security.Principal.GenericPrincipal(
user.Identity,
roleArray
);
// 让系统使用我们的拥有角色的用户对象
context.User = principal;
}
}
获取用户名
this.User.Identity.Name;
登出
FormsAuthentication.SignOut();