最近在看asp.net forum,對其中的驗證機制看得模模糊糊,看完構建安全的 ASP.NET 應用程式中的表單身分識別驗證部分,思路就很清晰了,稍做了點記錄,以便查閱:
構建基於forms的驗證機制過程如下:
1,設定IIS為可匿名訪問和asp.net web.config中設定為form驗證
2,檢索資料存放區驗證使用者,並檢索角色(如果不是基於角色可不用)
3,使用FormsAuthenticationTicket建立一個Cookie並回傳到用戶端,並儲存
角色到票中,如:
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是一個角色字串數組
string encryptedTicket = FormsAuthentication.Encrypt(authTicket); //加密
存入Cookie
HttpCookie authCookie =
new HttpCookie(FormsAuthentication.FormsCookieName,
encryptedTicket);
Response.Cookies.Add(authCookie);
4,在Application_AuthenticateRequest事件中處理常式中(Global.asax)中,使用
票建立IPrincipal對象並存在HttpContext.User中
代碼:
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);//解密
string[] roles = authTicket.UserData.Split(new char[]{';'});//根據存入時的格式分解,;或|....
Context.User = new GenericPrincipal(Context.User.Identity, Roles);//存在HttpContext.User中
5,需要對某些頁面進行角色控制,有兩種方法:
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設定優先於父目錄的web.config設定
這裡有一篇更全面的總結