在ASP.NET中如何用C#.NET實現基於表單的驗證
這篇文章引用到了Microsoft.NET類庫中的以下名空間:
System.Data.SqlClient
System.Web.Security
-------------------------------
任務:
摘要:
1.要求
2.用VisualC#.NET創建一個ASP.NET應用程序
3.在Web.config文件裏配置安全設置
4.創建一個數據庫表樣例來存放用戶資料
5.創建Logon.aspx頁麵
6.編寫事件處理代碼來驗證用戶身份
7.創建一個Default.aspx頁麵
8.附加提示
參考文章
-------------------------------
摘要
這篇文章示範了如何實現通過數據庫存儲用戶信息來實現基於表單的驗證.
(一)要求
需要以下工具來實現
1.MicrosoftVisualStudio.NET
2.MicrosoftInternetInformationServices(IIS)version5.0或者更新
3.MicrosoftSQLServer
(二)用C#.NET創建ASP.NET應用程序
1.打開VisualStudio.NET
2.建立一個新的ASP.NET Web應用程序,並且指定名稱和路徑.
(三)在Web.config文件裏配置安全設置
這一節示範了如何通過添加和修改<authentication>和<authorization>節點來配置ASP.NET應用程序以實現基於表單的驗證.
1.在解決方案窗口裏,打開Web.config文件.
2.把authentication模式改為Forms(注:默認為windows)
3.插入<Forms>標簽,並且填入適當的屬性.(請鏈接到在文章最後列出的MSDN文檔或者QuickStart文檔來查看這些屬性)先複製下麵的代碼,接著再把它粘貼到<authentication>節:
<authenticationmode="Forms"> <formname=".ASPXFORMSDEMO"loginUrl="logon.aspx"protection="All"path="/"timeout="30"/> </authentication> |
(注:如果不指定loginUrl,默認為default.aspx)
4.通過加入以下節點實現拒絕匿名訪問:
<authentication> <denyusers="?"/> <allowusers="*"/> </authentication> |
(四)創建一個數據庫表樣例來存放用戶資料
這一節示範了如何創建一個示例數據庫來存放用戶名,密碼,和用戶角色.如果你想要實現基於角色的安全就有必要在數據庫中添加一個存放用戶角色的字段.
1.打開記事本。
2.把下麵這段腳本複製到記事本然後保存:
ifexists(select*fromsysobjectswhereid= INSERTINTOUsersvalues('user1','user1','Manager') |
3.打開MicrosoftSQLServer,打開查詢分析器,在數據庫列表裏選擇Pubs數據庫,然後把上麵的腳本粘貼過來,運行。這時會在Pubs數據庫裏創建一個將會在這個示例程序中用到的示例用戶表。
(五)創建Logon.aspx頁麵
1.在已創建好的項目裏創建一個新的Web窗體,名為Logon.aspx。
2.在編輯器裏打開Logon.aspx,切換到HTML視圖。
3.複製下麵代碼,然後在編輯菜單裏“選擇粘貼為HTML”選項,插入到<form>標簽之間。
<h3> <fontface="Verdana">LogonPage</font> </h3> <table> <tr> <td>Email:</td> <td><inputtype="text"runat="server"></td> <td><ASP:RequiredFieldValidatorControlToValidate="txtUserName" Display="Static"ErrorMessage="*"runat="server" ID="vUserName"/></td> </tr> <tr> <td>Password:</td> <td><inputtype="password"runat="server"></td> <td><ASP:RequiredFieldValidatorControlToValidate="txtUserPass" Display="Static"ErrorMessage="*"runat="server" ID="vUserPass"/> </td> </tr> <tr> <td>PersistentCookie:</td> <td><ASP:CheckBoxrunat="server"autopostback="false"/></td> <td></td> </tr> </table> <inputtype="submit"Value="Logon"runat="server"ID="cmdLogin"><p></p> <asp:LabelForeColor="red"Font-Name="Verdana"Font-Size="10"runat="server"/> |
這個頁麵用來顯示一個登錄表單以便用戶可以提供他們的用戶名和密碼,並且記錄到應用程序中。
4.切換到設計視圖,保存這個頁麵。
(六)編寫事件處理代碼來驗證用戶身份
下麵這些代碼是放在後置代碼頁裏的(Logon.aspx.cs)
1.雙擊Logon頁麵打開Logon.aspx.cs文件。
2.在後置代碼文件裏導入必要的名空間:
usingSystem.Data.SqlClient; usingSystem.Web.Security; |
3.創建一個ValidateUser的函數,通過在數據庫中查找用戶來驗證用戶的身份。
(stringuserName,stringpassWord) { SqlConnectionconn; SqlCommandcmd; stringlookupPassword=null; //CheckforinvaliduserName. //userNamemustnotbenullandmustbebetween1and15characters. if((null==userName)||(0==userName.Length)||(userName.Length>15)) { System.Diagnostics.Trace.WriteLine("[ValidateUser]InputvalidationofuserNamefailed."); returnfalse; } //CheckforinvalidpassWord. //passWordmustnotbenullandmustbebetween1and25characters. if((null==passWord)||(0==passWord.Length)||(passWord.Length>25)) { System.Diagnostics.Trace.WriteLine("[ValidateUser]InputvalidationofpassWordfailed."); returnfalse; } try { //ConsultwithyourSQLServeradministratorforanappropriateconnection //stringtousetoconnecttoyourlocalSQLServer. conn=newSqlConnection("server=localhost;IntegratedSecurity=SSPI;database=pubs"); conn.Open(); //CreateSqlCommandtoselectpwdfieldfromuserstablegivensupplieduserName. cmd=newSqlCommand("Selectpwdfromuserswhere |
4.在cmdLogin_ServerLick事件裏使用下麵兩種方法中的一種來產生表單驗證的cookie並將頁麵轉到指定的頁麵。
下麵提供了兩種方法的示例代碼,根據你的需要來選擇。
a)在cmdLogin_ServerClick事件裏調用RedirectFromLoginPage方法來自動產生表單驗證cookie且將頁麵定向到一個指定的頁麵。
privatevoidcmdLogin_ServerClick(objectsender,System.EventArgse) { if(ValidateUser(txtUserName.value,txtUserPass.Value)) FormsAuthentication.RedirectFromLoginPage(txtUserName.Value,chkPresistCookie.Checked); else Response.Redirect("logon.aspx",true); } |
b)產生加密驗證票據,創建回應的cookie,並且重定向用戶。這種方式給了更多的控製權去讓你如何去創建cookie,你也可以連同FormsAuthenticationTicket一起包含一些自定義的數據。
privatevoidcmdLogin_ServerClick(objectsender,System.EventArgse) { if(ValidateUser(txtUserName.value,txtUserPass.Value)) { FormsAuthenticationTickettkt; stringcookiestr; HttpCookieck; tkt=newFormsAuthenticationTicket(1,txtUserName.value,DateTime.Now,DateTime.Now.AddMinutes(30),chkPersistCookie.Checked,"yourcustomdata");//創建一個驗證票據 cookiestr=FormsAuthentication.Encrypt(tkt);//並且加密票據 ck=newHttpCookie(FormsAuthentication.FormsCookieName,cookiestr);//創建cookie if(chkpersistCookie.Checked)//如果用戶選擇了保存密碼 ck.Expires=tkt.Expiratioin;//設置cookie有效期 ck.Path=FormsAuthentication.FormsCookiePath;//cookie存放路徑 Response.Cookies.Add(ck); stringstrRedirect; strRedirect=Request["ReturnUrl"]; if(strRedirect==null) strRedirect="default.aspx"; Response.Redirect(strRedirect,true); } else Reponse.Redirect("logon.aspx",true); } |
5.請確保在InititalizeComponent方法裏有如下代碼:
this.cmdLogin.ServerClick+=newSystem.EventHandler(this.cmdLogin_ServerClick); |
(七)創建一個Default.aspx頁麵
這一節創建一個測試頁麵用來作為當用戶驗證完之後重定向到的頁麵。如果用戶第一次沒有被記錄下來就瀏覽到這個頁,這時用戶將被重定向到登錄頁麵。
1.把現有的WebForm1.aspx重命名為Default.aspx,然後在編輯器裏打開。
2.切換到HTML視圖,複製以下代碼到<form>標簽之間:
<inputtype="submit"Value="SignOut"runat="server"> |
這個按鈕用來注銷表單驗證會話。
3.切換到設計視圖,保存頁麵。
4.在後置代碼裏導入必要的名空間:
usingSystem.Web.Security; |
5.雙擊SingOut按鈕打開後置代碼(Default.aspx.cs),然後把下麵代碼複製到cmdSingOut_ServerClick事件處理中:
privatevoidcmdSignOut_ServerClick(objectsender,System.EventArgse) { FormsAuthentication.SignOut();//注銷 Response.Redirect("logon.aspx",true); } |
6.請確認在InititalizeComponent方法中有以下代碼:
this.cmdSignOut.ServerClick+=newSystem.EventHandler(this.cmdSignOut_ServerClick); |
7.保存編譯項目,現在可以運行這個應用程序了。
(八)附加提示
1.如果想要在數據庫裏安全地存放密碼,可以在存放到數據到之前先用FormsAuthentication類裏的HashPasswordForStoringInConfigFile函數來加密。(注:將會產生一個哈希密碼)
2.可以在配置文件(Web.config)裏存放SQL連接信息,以便當需要時方便修改。
3.可以增加一些代碼來防止黑客使用窮舉法來進行登錄。例如,增加一些邏輯使用戶隻能有兩三次的登錄機會。如果用戶在指定的登錄次數裏無法登錄的話,可以在數據庫裏設置一個標誌符來防止用戶登錄直到此用戶訪問另一個頁麵或者請示你的幫助。另外,也可以在需要時增加一些適當的錯誤處理。
4.因為用戶是基於驗證cookie來識別的,所以可以在應用程序裏使用安全套接層(SSL)來保護驗證cookie和其它有用的信息。
5.基於表單的驗證方式要求客戶端的遊覽器接受或者啟用cookies.
6.在<authentication>配置節裏的timeout參數用來控製驗證cookies重新產生的間隔時間。可以給它賦一個適當的值來提供更好的性能和安全性。
7.在Internet上的一些代理服務器或者緩衝可能會緩存一些將會重新返回給另外一個用戶的包含Set-Cookie頭的Web服務器響應。因為基於表單的驗證是使用cookie來驗證用戶的,所以通過中間代理服務器或者緩衝的話可能會引起用戶會被意外地搞錯為原本不是要發送給他的用戶。
最後更新:2017-04-02 00:06:35