(五)創建logon.aspx頁面
1.在已創建好的項目里創建一個新的web 窗體,名為logon.aspx。
2.在編輯器里打開logon.aspx,切換到html視圖。
3.復制下面代碼,然后在編輯菜單里“選擇粘貼為html”選項,插入到<form>標簽之間。
 1<h3>
 2   <font face="verdana">logon page</font>
 3</h3>
 4<table>
 5   <tr>
 6      <td>email:</td>
 7      <td><input id="txtusername" type="text" runat="server"></td>
 8      <td><asp:requiredfieldvalidator controltovalidate="txtusername"
 9           display="static" errormessage="*" runat="server" 
10           id="vusername" /></td>
11   </tr>
12   <tr>
13      <td>password:</td>
14      <td><input id="txtuserpass" type="password" runat="server"></td>
15      <td><asp:requiredfieldvalidator controltovalidate="txtuserpass"
16          display="static" errormessage="*" runat="server" 
17          id="vuserpass" />
18      </td>
19   </tr>
20   <tr>
21      <td>persistent cookie:</td>
22      <td><asp:checkbox id="chkpersistcookie" runat="server" autopostback="false" /></td>
23      <td></td>
24   </tr>
25</table>
26<input type="submit" value="logon" runat="server" id="cmdlogin"><p></p>
27<asp:label id="lblmsg" forecolor="red" font-name="verdana" font-size="10" runat="server" />
28這個頁面用來顯示一個登錄表單以便用戶可以提供他們的用戶名和密碼,并且記錄到應用程序中。
4.切換到設計視圖,保存這個頁面。
(六)編寫事件處理代碼來驗證用戶身份
 下面這些代碼是放在后置代碼頁里的(logon.aspx.cs)
1.雙擊logon頁面打開logon.aspx.cs文件。
2.在后置代碼文件里導入必要的名空間:
  using system.data.sqlclient;
  using system.web.security;
3.創建一個validateuser的函數,通過在數據庫中查找用戶來驗證用戶的身份。(請改變數據庫連接字符串來指向你的數據庫)
 1private bool validateuser( string username, string password )
 2{
 3sqlconnection conn;
 4sqlcommand cmd;
 5string lookuppassword = null;
 6
 7// check for invalid username.
 8// username must not be null and must be between 1 and 15 characters.
 9if ( (  null == username ) || ( 0 == username.length ) || ( username.length > 15 ) )
10{
11  system.diagnostics.trace.writeline( "[validateuser] input validation of username failed." );
12  return false;
13}
14
15// check for invalid password.
16// password must not be null and must be between 1 and 25 characters.
17if ( (  null == password ) || ( 0 == password.length ) || ( password.length > 25 ) )
18{
19  system.diagnostics.trace.writeline( "[validateuser] input validation of password failed." );
20  return false;
21}
22
23try
24{
25  // consult with your sql server administrator for an appropriate connection
26  // string to use to connect to your local sql server.
27  conn = new sqlconnection( "server=localhost;integrated security=sspi;database=pubs" );
28  conn.open();
29
30  // create sqlcommand to select pwd field from users table given supplied username.
31  cmd = new sqlcommand( "select pwd from users where [email protected]", conn );
32  cmd.parameters.add( "@username", sqldbtype.varchar, 25 );
33  cmd.parameters["@username"].value = username;
34
35  // execute command and fetch pwd field into lookuppassword string.
36  lookuppassword = (string) cmd.executescalar();
37
38  // cleanup command and connection objects.
39  cmd.dispose();
40  conn.dispose();
41}
42catch ( exception ex )
43{
44  // add error handling here for debugging.
45  // this error message should not be sent back to the caller.
46  system.diagnostics.trace.writeline( "[validateuser] exception " + ex.message );
47}
48
49// if no password found, return false.
50if ( null == lookuppassword ) 
51{
52  // you could write failed login attempts here to event log for additional security.
53  return false;
54}
55
56// compare lookuppassword and input password, using a case-sensitive comparison.
57return ( 0 == string.compare( lookuppassword, password, false ) );
58
59}
60
(注:這段代碼的意思是先判斷輸入的用戶名和密碼是否符合一定的條件,如上,如果符合則連接到數據庫,并且根據用戶名來取出密碼并返回密碼,最后再判斷取出的密碼是否為空,如果不為空則再判斷取出的密碼和輸入的密碼是否相同,最后的false參數為不區分大小寫)
4.在cmdlogin_serverlick事件里使用下面兩種方法中的一種來產生表單驗證的cookie并將頁面轉到指定的頁面。
下面提供了兩種方法的示例代碼,根據你的需要來選擇。
a)在cmdlogin_serverclick事件里調用redirectfromloginpage方法來自動產生表單驗證cookie且將頁面定向到一個指定的頁面。
private void cmdlogin_serverclick(object sender,system.eventargs e)
{
  if(validateuser(txtusername.value,txtuserpass.value))
   formsauthentication.redirectfromloginpage(txtusername.value,chkpresistcookie.checked);
   else
    response.redirect("logon.aspx",true);   
}
b)產生加密驗證票據,創建回應的cookie,并且重定向用戶。這種方式給了更多的控制權去讓你如何去創建cookie,你也可以連同formsauthenticationticket一起包含一些自定義的數據。
 1private void cmdlogin_serverclick(object sender,system.eventargs e)
 2{
 3  if(validateuser(txtusername.value,txtuserpass.value)) 
 4  {
 5   formsauthenticationticket tkt;
 6   string cookiestr;
 7   httpcookie ck;
 8   tkt=new formsauthenticationticket(1,txtusername.value,datetime.now,datetime.now.addminutes(30),chkpersistcookie.checked,"your custom data"); //創建一個驗證票據
 9   cookiestr=formsauthentication.encrypt(tkt);//并且加密票據
10   ck=new httpcookie(formsauthentication.formscookiename,cookiestr);// 創建cookie
11   if(chkpersistcookie.checked) //如果用戶選擇了保存密碼
12    ck.expires=tkt.expiratioin;//設置cookie有效期
13    ck.path=formsauthentication.formscookiepath;//cookie存放路徑
14   response.cookies.add(ck);
15   string strredirect;
16   strredirect=request["returnurl"];
17   if(strredirect==null)
18    strredirect="default.aspx";
19   response.redirect(strredirect,true);
20  }
21  else
22   reponse.redirect("logon.aspx",true);
23}
245.請確保在inititalizecomponent方法里有如下代碼:
   this.cmdlogin.serverclick += new system.eventhandler(this.cmdlogin_serverclick);
(七)創建一個default.aspx頁面
這一節創建一個測試頁面用來作為當用戶驗證完之后重定向到的頁面。如果用戶第一次沒有被記錄下來就瀏覽到這個頁,這時用戶將被重定向到登錄頁面。
  1.把現有的webform1.aspx重命名為default.aspx,然后在編輯器里打開。
  2.切換到html視圖,復制以下代碼到<form>標簽之間:
<input type="submit" value="signout" runat="server" id="cmdsignout">
這個按鈕用來注銷表單驗證會話。
  3.切換到設計視圖,保存頁面。
  4.在后置代碼里導入必要的名空間:
using system.web.security;
  5.雙擊singout按鈕打開后置代碼(default.aspx.cs),然后把下面代碼復制到cmdsingout_serverclick事件處理中:
  private void cmdsignout_serverclick(object sender,system.eventargs e)
  {
   formsauthentication.signout();//注銷 
   response.redirect("logon.aspx",true);
  }
  6.請確認在inititalizecomponent方法中有以下代碼:
  this.cmdsignout.serverclick += new system.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來驗證用戶的,所以通過中間代理服務器或者緩沖的話可能會引起用戶會被意外地搞錯為原本不是要發送給他的用戶。
   
   
參考文章:
  如果想要知道如何通過配置<credentials>節點存放用戶名和密碼來實現基于表單的驗證的話,請參考以下gotdotnet asp.net quickstart示例:
  基于表單的驗證:http://www.gotdotnet.com/quickstart/aspplus/default.aspx?url=/quickstart/aspplus/doc/formsauth.aspx
  如果想要知道如何使用xml文件來存放用戶名和密碼來實現基于表單的驗證的話,請參考sdk文檔的以下示例:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconcookieauthenticationusinganxmlusersfile.asp
  如果想要知道更多的關于asp.net安全的話,請參考microsoft .net framework developer's guide文檔:
asp.net 安全:  http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconaspnetwebapplicationsecurity.asp
   如果想知道更多關于system.web.security名空間的話,請參考:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemwebsecurity.asp
  如果想知道更多的關于asp.net配置的話,請參考microsoft .net framework developer's guide文檔:
asp.net配置:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconaspnetconfiguration.asp
asp.net配置節點:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpgrfaspnetconfigurationsections.asp
  如果想知道更多關于asp.net安全指導的話,請參考msdn:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/authaspdotnet.asp
  如果想知道更多關于asp.net的,請參考msdn新聞組:
http://go.microsoft.com/fwlink/?linkid=5811&clcid=0x409
這篇文章適用于:
microsoft asp.net (included with the .net framework 1.1)
microsoft visual c# .net (2003)
microsoft asp.net (included with the .net framework) 1.0
microsoft visual c# .net (2002)
microsoft sql server 2000 (all editions)
microsoft sql server 7.0
microsoft sql server 2000 64 bit (all editions)
新聞熱點
疑難解答
圖片精選