天天看点

[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,由于时间的关系,就记录这些,如果有什么错误或更好的方法请大家指出,谢谢。