天天看點

[ASP.NET使用者驗證一]Forms驗證

 使用者驗證是每一個項目必須的一個子產品,由于已經很久沒有碰到這一塊内容,今天寫一個使用者驗證居然腦子一片空白。于是乎就和一個同僚進行了一片讨論,晚上回家決定把讨論的結果給記錄下來,以備後來之需。在ASP.NET中有幾種 使用者驗證的方法:Windows驗證,Forms驗證和Passport驗證。當然使用者也可以自定義與驗證方法,而最常用的莫過于Forms驗證,這也是今天所要讨論的驗證方式。

    Forms驗證方式首先要配置的是web.config檔案,把authentication節點配置為Forms驗證,而它預設的是Windows驗證。再修改配置檔案時,還要注意大小寫,因為XML檔案是大小寫敏感的,修改後authentication節點如下所示,其中還包含了一些form的配置參數。

 1           < authentication  mode ="Forms" >

 2               < forms 

 3                   protection ="All"  

 4                  timeout ="20"  

 5                  name =".XDOTNET"  

 6                  loginUrl ="SignIn.aspx"  

 7                  defaultUrl ="Default.aspx"  

 8                  path ="/"  

 9                  requireSSL ="false"  

10                  enableCrossAppRedirects ="false"

11                   >

12               </ forms >

13           </ authentication >     關于forms節點的屬性在後面介紹FormsAuthetication類的有關成員時,再介紹它們的用處。使用者驗證,顧名思義就是驗證使用者的合理性,當使用者登入到網站時,驗證輸入的使用者名和密碼是否和資料庫中存儲的資料相符合。其實很簡單,有一種快速的方法,這種驗證方法 很适合背景管理的驗證,因為當我們關閉浏覽器時驗證就會失效。

 1           public   static   bool  ValidUser( string  userName,  string  password) 

 2          {

 3               if  ( ! string .IsNullOrEmpty(userName)  &&   ! string .IsNullOrEmpty(password)) 

 4              {

 5                  password  =  FormsAuthentication.HashPasswordForStoringInConfigFile(password,  "MD5" );

 6                   string  realPassword  =  Users.GetUser(userName).Password;

 7                   if  ( string .Compare(password, realPassword,  true )  ==   0 ) 

 8                  {

 9                      FormsAuthentication.SetAuthCookie(userName, false);

10                       return   true ;

11                  }

12              }

13               return   false ;

14          }     上面的方法就可以驗證以32位MD5加密的Password的資料驗證,其中Users.GetUser(string)這個方法是通過使用者名從資料庫中取得使用者執行個體。當使用者合理時,通過FormsAuthentication.SetAuthCookie方法 将為使用者(以使用者名)建立一個身份驗證票證,并将其添加到響應的 Cookie 集合或 URL(cookieless)。這樣就實作了使用者驗證的過程,那麼我們怎麼得到使用者是否通過驗證呢?微軟把程式不斷的進行封裝,不斷的傻瓜化,當然想得到目前使用者是否通過驗證也很簡單,代碼如下:

1         public   static   bool  IsAuthenticated() 

2          {

3               return  HttpContext.Current.User.Identity.IsAuthenticated;

4          }     是不是很簡單呢?當使用者(隻要背景管理驗證的情況下)驗證隻要這兩個步驟就OK了,當使用者登入如調用ValidUser方法,當載入頁面時通過IsAuthenticated方法判斷目前使用者是否通過驗證。這樣一個使用者驗證子產品也就完成了,但是在現代的網絡中,使用者是相當的值錢的東東,每個網站都會想留住很多的使用者;有時有些東西隻允許會員才能夠檢視等等,這樣就需要更好的驗證。使使用者關閉浏覽器後,在一段特定時間内還處于通過驗證狀态。這就需要操作和設定驗證的票據FormsAuthenticationTicket,代碼如下。

 1           public   static   bool  ValidUser( string  userName,  string  password) 

 2          {

 3               if  ( ! string .IsNullOrEmpty(userName)  &&   ! string .IsNullOrEmpty(password)) 

 4              {

 5                  password  =  FormsAuthentication.HashPasswordForStoringInConfigFile(password,  " MD5 " );

 6                   string  realPassword  =  Users.GetUser(userName).Password;

 7                   if  ( string .Compare(password, realPassword,  true )  ==   0 ) 

 8                  {

 9                      FormsAuthenticationTicket ticket  =   new  FormsAuthenticationTicket( 1 ,

10                          userName,

11                          DateTime.Now,

12                          DateTime.Now.AddMinutes( 20 ),

13                           false ,

14                           null // 可以将Roles按","分割成字元串,寫入cookie

15                          );

16                       string  data  =  FormsAuthentication.Encrypt(ticket);

17                      HttpCookie cookie  =   new  HttpCookie(FormsAuthentication.FormsCookieName, data);

18                      cookie.Path  =  FormsAuthentication.FormsCookiePath;

19                      cookie.Domain  =  FormsAuthentication.CookieDomain;

20                      cookie.Expires  =  ticket.Expiration;

21                      HttpContext.Current.Response.Cookies.Add(cookie);

22                       return   true ;

23                  }

24              }

25               return   false ;

26          }     從代碼中看到的FormsCookiePath,CookieDomain等等就是從配置檔案中獲得,關于其它的FormsAuthentication成員可以通路MSDN( FormsAuthentication )。我們同樣也可以通過HttpContext.Current.User對象來判斷目前使用者的狀況,也可以用IsInRole方法來判斷使用者的角色。當然當我們驗證使用者後,要把使用者加入到Http上下文HttpContext的目前請求的User對象中,代碼如下:

1                     FormsIdentity identity  =   new  FormsIdentity(ticket);

2                      GenericPrincipal user  =   new  GenericPrincipal(identity,  new   string [] { });

3                      HttpContext.Current.User  =  user;     這樣就完成了驗證的全過程。至于檢視使用者的Cookie判斷使用者是否存在記錄狀态(如:記錄1個月,1天,1年等等),可以在管道中進行判斷和編寫,這裡就不再贅述。OK,由于時間的關系,就記錄這些,如果有什麼錯誤或更好的方法請大家指出,謝謝。