程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> ASP.NET Form驗證隨筆

ASP.NET Form驗證隨筆

編輯:.NET實例教程

以前的項目遇到用戶驗證問題全都采用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)
                    {
 &n
bsp;                      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驗證是否就失效了呢?

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved