日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

在ASP.NET中如何用C#.NET实现基于表单的验证

發布時間:2023/11/27 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 在ASP.NET中如何用C#.NET实现基于表单的验证 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這篇文章引用到了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 窗體,名為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的函數,通過在數據庫中查找用戶來驗證用戶的身份。(請改變菘飭幼址粗趕蚰愕氖菘猓?BR>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上的一些代理服務器或者緩沖可能會緩存一些將會重新返回給另外一個用戶的包含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)
?

總結

以上是生活随笔為你收集整理的在ASP.NET中如何用C#.NET实现基于表单的验证的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。