最近在看 forum,對其中的驗(yàn)證機(jī)制看得模模糊糊,看完構(gòu)建安全的 ASP.NET 應(yīng)用程序中的表單身份驗(yàn)證部分,思路就很清晰了,稍做了點(diǎn)記錄,以便查閱:
構(gòu)建基于forms的驗(yàn)證機(jī)制過程如下:
1,設(shè)置IIS為可匿名訪問和 web.config中設(shè)置為form驗(yàn)證
2,檢索數(shù)據(jù)存儲驗(yàn)證用戶,并檢索角色(如果不是基于角色可不用)
3,使用FormsAuthenticationTicket創(chuàng)建一個Cookie并回發(fā)到客戶端,并存儲
角色到票中,如:
FormsAuthentication.SetAuthCookie(Username,true | false)
cookies保存時間:
HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName].Expires=DateTime.Now.AddDays(1)
如果需要存儲角色,采用:
FormsAuthenticationTicket authTicket = new
FormsAuthenticationTicket(
1, // version
txtUserName.Text, // user name
DateTime.Now, // creation
DateTime.Now.AddMinutes(20),// Expiration
false, // Persistent
roles ); // User data
roles是一個角色字符串?dāng)?shù)組
string encryptedTicket = FormsAuthentication.Encrypt(authTicket); //加密
存入Cookie
HttpCookie authCookie =
new HttpCookie(FormsAuthentication.FormsCookieName,
encryptedTicket);
Response.Cookies.Add(authCookie);
4,在Application_AuthenticateRequest事件中處理程序中(Global.asax)中,使用
票創(chuàng)建IPrincipal對象并存在HttpContext.User中
代碼:
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);//解密
string[] roles = authTicket.UserData.Split(new char[]{';'});//根據(jù)存入時的格式分解,;或|....
Context.User = new GenericPrincipal(Context.User.Identity, Roles);//存在HttpContext.User中
5,需要對某些頁面進(jìn)行角色控制,有兩種方法:
5.1,web.config中加
<location path="EditPost.aspx">
<system.web>
<authorization>
<allow roles="RoleName" />
<deny users="?" />
</authorization>
</system.web>
</location>
5.2,把只能是某種角色訪問的文件放在同一目錄下,在此目錄下添加一個web.config
<configuration>
<system.web>
<authorization>
<allow roles="RoleName" />
<deny users="*" />
</authorization>
</system.web>
</configuration>
說明:子目錄的web.config設(shè)置優(yōu)先于父目錄的web.config設(shè)置