以前的项目遇到用户验证问题全都采用windows验证方式,最近公司项目中要求采用Forms验证方式。
总结如下:
1.登录页面代码
PRotected void Button1_Click(object sender, EventArgs e)
{
FormsAuthenticationTicket ticket=new FormsAuthenticationTicket (1,"LoginName",DateTime.Now,DateTime.Now.AddMinutes(20),false,"aaa",FormsAuthentication.FormsCookiePath);
HttpCookie cookie=new HttpCookie(FormsAuthentication.FormsCookieName,FormsAuthentication.Encrypt(ticket));
if(ticket.IsPersistent)
{
cookie.Expires = ticket.Expiration;
}
Response.Cookies.Add(cookie);
Response.Redirect("admin_page1.aspx");
}
2. Webconfig代码
<authentication mode="Forms" >
<forms name="authTest" loginUrl="~/admin/admin_login.aspx" timeout="20">
</forms>
</authentication>
</system.web>
<location path="admin">
<system.web>
<authorization>
<allow roles="admin,aaa"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
3.Global文件代码
添加application_AuthenticateRequest事件
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
string userData;
string[] roles;
userData = string.Empty;
try
{
if (Request.Cookies["authTest"] != null)
{
FormsAuthenticationTicket ticket =
FormsAuthentication.Decrypt(Request.Cookies["authTest"].Value);
if (ticket != null)
{
userData = ticket.UserData;
}
}
}
catch (Exception E)
{
HttpContext.Current.Response.Write("<!-- " + E.Message + " -->");
}
roles = userData.Split(',');
HttpContext.Current.User = new GenericPrincipal(HttpContext.Current.User.Identity, roles);
}
}
}
到此完成了Forms验证。
但我有疑问:如果客户端禁用了cookie那么forms验证是否就失效了呢?
新闻热点
疑难解答