WEB开发网
开发学院WEB开发ASP.NET ASP.NET Form验证随笔 阅读

ASP.NET Form验证随笔

 2009-03-25 17:42:27 来源:WEB开发网   
核心提示:以前的项目遇到用户验证问题全都采用windows验证方式,最近公司项目中要求采用Forms验证方式,ASP.NET Form验证随笔,总结如下:1.登录页面代码 PRotected void Button1_Click(object sender, EventArgs e) { FormsAuthenticatio

以前的项目遇到用户验证问题全都采用windows验证方式,最近公司项目中要求采用Forms验证方式。

总结如下:

1.登录页面代码

 PRotected void Button1_Click(object sender, EventArgs e)
     {

       FormsAuthenticationTicket ticket=new FormsAuthenticationTicket  (1,"LoginName",DateTime.Now,DateTime.Now.AddMinutes(20),false,"aaa",FormsAuthentication.FormsCookiePath);
         HttpCookie cookie=new HttpCookie(FormsAuthentication.FormsCookieName,FormsAuthentication.Encrypt(ticket));
         if(ticket.IsPersistent)
         {
           cookie.Expires = ticket.Expiration;
         }
         Response.Cookies.Add(cookie);


         Response.Redirect("admin_page1.aspx");
     }

2. Webconfig代码

<authentication mode="Forms" >
     <forms name="authTest" loginUrl="~/admin/admin_login.aspx" timeout="20">
     </forms>
    </authentication>
   </system.web>
  <location path="admin">
   <system.web>
    <authorization>
     <allow roles="admin,aaa"/>
     <deny users="*"/>
    </authorization>
   </system.web>
  </location>

3.Global文件代码

添加application_AuthenticateRequest事件

 if (HttpContext.Current.User != null)
       {
         if (HttpContext.Current.User.Identity.IsAuthenticated)
         {
           if (HttpContext.Current.User.Identity is FormsIdentity)
           {
             string userData;
             string[] roles;

           userData = string.Empty;
             try
             {
               if (Request.Cookies["authTest"] != null)
               {
                 FormsAuthenticationTicket ticket =
                   FormsAuthentication.Decrypt(Request.Cookies["authTest"].Value);
                 if (ticket != null)
                 {
                   userData = ticket.UserData;
                 }
               }
             }
             catch (Exception E)
             {
               HttpContext.Current.Response.Write("<!-- " + E.Message + " -->");
             }
             roles = userData.Split(',');
             HttpContext.Current.User = new GenericPrincipal(HttpContext.Current.User.Identity, roles);
           }
         }
       }

到此完成了Forms验证。

但我有疑问:如果客户端禁用了cookie那么forms验证是否就失效了呢?

Tags:ASP NET Form

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接