以前的項目遇到用戶驗證問題全都采用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)
{
&n
bsp; 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驗證是否就失效了呢?