在ASP.NET中如何用C#.NET實現基於表單的驗證

來源:互聯網
上載者:User
翻譯:mydotnet

    這篇文章引用到了Microsoft .NET類庫中的以下名空間:
     System.Data.SqlClient
     System.Web.Security
-------------------------------
   任務:
   摘要: 
  1.要求
  2.用Visual C#.NET 建立一個ASP.NET 應用程式
  3.在Web.config檔案裡配置安全設定
  4.建立一個資料庫表範例來存放使用者資料
  5.建立Logon.aspx頁面
  6.編寫事件處理代碼來驗證使用者身份
  7.建立一個Default.aspx頁面
  8.附加提示
參考文章
-------------------------------
摘要
 這篇文章示範了如何?通過資料庫儲存使用者資訊來實現基於表單的驗證.
(一)要求
 需要以下工具來實現
1.Microsoft Visual Studio.NET
2.Microsoft Internet Information Services(IIS) version 5.0 或者更新
3.Microsoft SQL Server
(二)用C#.NET建立ASP.NET應用程式
1.開啟Visual Studio.NET
2.建立一個新的ASP.NET Web應用程式,並且指定名稱和路徑.
(三)在Web.config檔案裡配置安全設定
這一節示範了如何通過添加和修改<authentication>和<authorization>節點來配置ASP.NET應用程式以實現基於表單的驗證.
1.在解決方案視窗裡,開啟Web.config檔案.
2.把authentication模式改為Forms(註:預設為windows)
3.插入<Forms>標籤,並且填入適當的屬性.(請連結到在文章最後列出的MSDN文檔或者QuickStart文檔來查看這些屬性)先複製下面的代碼,接著再把它粘貼到<authentication>節:

<authentication mode="Forms">
<form name=".ASPXFORMSDEMO" loginUrl="logon.aspx" protection="All" path="/" timeout="30"/>
</authentication>
(註:如果不指定loginUrl,預設為default.aspx)

4.通過加入以下節點實現拒絕匿名訪問:
<authentication>
<deny users="?"/>
<allow users="*"/>
</authentication>

(四)建立一個資料庫表範例來存放使用者資料
這一節示範了如何建立一個樣本資料庫來存放使用者名稱,密碼,和使用者角色.如果你想要實現基於角色的安全就有必要在資料庫中添加一個存放使用者角色的欄位.
1.開啟記事本。
2.把下面這段指令碼複製到記事本然後儲存:

if exists (select * from sysobjects where id =
object_id(N'[dbo].[Users]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Users]
GO
CREATE TABLE [dbo].[Users] (
   [uname] [varchar] (15) NOT NULL ,
   [Pwd] [varchar] (25) NOT NULL ,
   [userRole] [varchar] (25) NOT NULL ,
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Users] WITH NOCHECK ADD
   CONSTRAINT [PK_Users] PRIMARY KEY  NONCLUSTERED
   (
      [uname]
   )  ON [PRIMARY]
GO

INSERT INTO Users values('user1','user1','Manager')
INSERT INTO Users values('user2','user2','Admin')
INSERT INTO Users values('user3','user3','User')
GO
3.開啟Microsoft SQL Server,開啟查詢分析器,在資料庫列表裡選擇Pubs資料庫,然後把上面的指令碼粘貼過來,運行。這時會在Pubs資料庫裡建立一個將會在這個樣本程式中用到的樣本使用者表。
(五)建立Logon.aspx頁面
1.在已建立好的項目裡建立一個新的Web Form,名為Logon.aspx。
2.在編輯器裡開啟Logon.aspx,切換到HTML視圖。
3.複製下面代碼,然後在編輯菜單裡“選擇粘貼為HTML”選項,插入到<form>標籤之間。
<h3>
   <font face="Verdana">Logon Page</font>
</h3>
<table>
   <tr>
      <td>Email:</td>
      <td><input id="txtUserName" type="text" runat="server"></td>
      <td><ASP:RequiredFieldValidator ControlToValidate="txtUserName"
           Display="Static" ErrorMessage="*" runat="server"
           ID="vUserName" /></td>
   </tr>
   <tr>
      <td>Password:</td>
      <td><input id="txtUserPass" type="password" runat="server"></td>
      <td><ASP:RequiredFieldValidator ControlToValidate="txtUserPass"
          Display="Static" ErrorMessage="*" runat="server"
          ID="vUserPass" />
      </td>
   </tr>
   <tr>
      <td>Persistent Cookie:</td>
      <td><ASP:CheckBox id="chkPersistCookie" runat="server" autopostback="false" /></td>
      <td></td>
   </tr>
</table>
<input type="submit" Value="Logon" runat="server" ID="cmdLogin"><p></p>
<asp:Label id="lblMsg" ForeColor="red" Font-Name="Verdana" Font-Size="10" runat="server" />

 這個頁面用來顯示一個登入表單以便使用者可以提供他們的使用者名稱和密碼,並且記錄到應用程式中。
4.切換到設計檢視,儲存這個頁面。

(六)編寫事件處理代碼來驗證使用者身份
 下面這些代碼是放在後置字碼頁裡的(Logon.aspx.cs)
1.雙擊Logon頁面開啟Logon.aspx.cs檔案。
2.在後置代碼檔案裡匯入必要的名空間:
  using System.Data.SqlClient;
  using System.Web.Security;
3.建立一個ValidateUser的函數,通過在資料庫中尋找使用者來驗證使用者的身份。(請改變資料庫連接字串來指向你的資料庫)
private bool ValidateUser( string userName, string passWord )
{
SqlConnection conn;
SqlCommand cmd;
string lookupPassword = null;

// Check for invalid userName.
// userName must not be null and must be between 1 and 15 characters.
if ( (  null == userName ) || ( 0 == userName.Length ) || ( userName.Length > 15 ) )
{
  System.Diagnostics.Trace.WriteLine( "[ValidateUser] Input validation of userName failed." );
  return false;
}

// Check for invalid passWord.
// passWord must not be null and must be between 1 and 25 characters.
if ( (  null == passWord ) || ( 0 == passWord.Length ) || ( passWord.Length > 25 ) )
{
  System.Diagnostics.Trace.WriteLine( "[ValidateUser] Input validation of passWord failed." );
  return false;
}

try
{
  // Consult with your SQL Server administrator for an appropriate connection
  // string to use to connect to your local SQL Server.
  conn = new SqlConnection( "server=localhost;Integrated Security=SSPI;database=pubs" );
  conn.Open();

  // Create SqlCommand to select pwd field from users table given supplied userName.
  cmd = new SqlCommand( "Select pwd from users where uname=@userName", conn );
  cmd.Parameters.Add( "@userName", SqlDbType.VarChar, 25 );
  cmd.Parameters["@userName"].Value = userName;

  // Execute command and fetch pwd field into lookupPassword string.
  lookupPassword = (string) cmd.ExecuteScalar();

  // Cleanup command and connection objects.
  cmd.Dispose();
  conn.Dispose();
}
catch ( Exception ex )
{
  // Add error handling here for debugging.
  // This error message should not be sent back to the caller.
  System.Diagnostics.Trace.WriteLine( "[ValidateUser] Exception " + ex.Message );
}

// If no password found, return false.
if ( null == lookupPassword )
{
  // You could write failed login attempts here to event log for additional security.
  return false;
}

// Compare lookupPassword and input passWord, using a case-sensitive comparison.
return ( 0 == string.Compare( lookupPassword, passWord, false ) );

}
(註:這段代碼的意思是先判斷輸入的使用者名稱和密碼是否符合一定的條件,如上,如果符合則串連到資料庫,並且根據使用者名稱來取出密碼並返回密碼,最後再判斷取出的密碼是否為空白,如果不為空白則再判斷取出的密碼和輸入的密碼是否相同,最後的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一起包含一些自訂的資料。
private void cmdLogin_ServerClick(object sender,System.EventArgs e)
{
  if(ValidateUser(txtUserName.value,txtUserPass.Value))
  {
   FormsAuthenticationTicket tkt;
   string cookiestr;
   HttpCookie ck;
   tkt=new FormsAuthenticationTicket(1,txtUserName.value,DateTime.Now,DateTime.Now.AddMinutes(30),chkPersistCookie.Checked,"your custom data"); //建立一個驗證票據
   cookiestr=FormsAuthentication.Encrypt(tkt);//並且加密票據
   ck=new HttpCookie(FormsAuthentication.FormsCookieName,cookiestr);// 建立cookie
   if(chkpersistCookie.Checked) //如果使用者選擇了儲存密碼
    ck.Expires=tkt.Expiratioin;//設定cookie有效期間
    ck.Path=FormsAuthentication.FormsCookiePath;//cookie存放路徑
   Response.Cookies.Add(ck);
   string strRedirect;
   strRedirect=Request["ReturnUrl"];
   if(strRedirect==null)
    strRedirect="default.aspx";
   Response.Redirect(strRedirect,true);
  }
  else
   Reponse.Redirect("logon.aspx",true);
}
  5.請確保在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上的一些Proxy 伺服器或者緩衝可能會緩衝一些將會重新返回給另外一個使用者的包含Set-Cookie頭的Web伺服器響應。因為基於表單的驗證是使用cookie來驗證使用者的,所以通過中間Proxy 伺服器或者緩衝的話可能會引起使用者會被意外地搞錯為原本不是要發送給他的使用者。
   
   
參考文章:
  如果想要知道如何通過配置<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)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.