首页 >> 技术荟萃  
 
构建基于forms的验证机制过程
 
 
发布时间: 2007-02-26 14:26:05
 
最近在看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)chemas-microsoft-comSurprisefficeSurpriseffice" />>>
  如果需要存储角色,采用:
 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设置>>
 >>
 
   
 
收藏此页】【 】【打印】【关闭