這篇文章引用到了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 [email protected]", 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)
新聞熱點
疑難解答
圖片精選