在ASP.NET中如何用C#.NET實現基於表單的驗證
在ASP.NET中如何用C#.NET實現基於表單的驗證
翻譯: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 窗體,名為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上的一些代理伺服器或者緩衝可能會快取一些將會重新返回給另外一個使用者的包含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中基於Forms驗證的角色驗證授權ASP.NETORM
- 純CSS實現表單驗證CSS
- 實現elementUI表單的全域性驗證UI
- 如何用 Visual C#.net 中的 DTD、 XDR,或 XSD 驗證 XML 文件C#XML
- 利用jQuery實現表單驗證功能jQuery
- node實現基於token的身份驗證
- 如何使用angularjs實現表單驗證AngularJS
- RxJava2 實戰知識梳理(7) 基於 combineLatest 實現的輸入表單驗證RxJava
- 在 SpringBoot 專案中簡單實現 JWT 驗證Spring BootJWT
- Seam中的JSF表單驗證JS
- 實現基於JWT的Token登入驗證功能JWT
- Spring Security——基於表單登入認證原理及實現Spring
- Java隨機生成圖片與HTML表單中的驗證碼實現Java隨機HTML
- 在Keycloak中實現多租戶並在ASP.NET Core下進行驗證ASP.NET
- 【Hover】ASP.Net實現驗證碼!ASP.NET
- angular中關於表單動態驗證的一種新思路Angular
- jQuery實現的表單註冊驗證程式碼例項jQuery
- 基於Node.js實現行為驗證碼Node.js
- 在ASP.NET下實現數字和字元相混合的驗證碼ASP.NET字元
- 5.3. 驗證 Seam安全中的驗證特性是基於JAAS
- JavaScript 表單及表單驗證JavaScript
- 從零實現一個Vue表單驗證外掛Vue
- angular中的表單資料自定義驗證Angular
- bootstrap表單驗證boot
- javascript表單驗證JavaScript
- Laravel 表單驗證Laravel
- JavaScript 表單驗證JavaScript
- Django表單驗證Django
- jquery 表單驗證jQuery
- Js表單驗證JS
- vue 實戰表單驗證規則Vue
- 前端表單驗證的目的前端
- 在ASP.NET下實現數字和字元相混合的驗證碼 (轉)ASP.NET字元
- 基於Oauth2.0實現SSO單點認證OAuth
- Asp.net(C#)實現驗證碼功能ASP.NETC#
- 基於 URL 的縮圖在 Laravel 中的實現Laravel
- Asp.net MVC中表單驗證ASP.NETMVC
- 基於 Formily 的表單設計器實現原理分析 ORM