作者:微軟
本文的發佈號曾爲 CHS301240
有關本文的 Microsoft Visual Basic .NET 版本,請參閱 308157。
在 Web.config 文件中配置安全設置
本節介紹如何添加和修改 authentication
和 authorization
配置部分,以便將 ASP.NET 應用程序配置爲使用基於窗體的身份驗證。
1.
在項目資源管理器中,打開 Web.config 文件。
2.
將身份驗證模式更改爲Forms
(窗體)。
3.
插入 Forms 標記,並填入相應的屬性。(有關這些屬性的更多信息,請參閱 參考
一節中列出的 MSDN 文檔或快速入門文檔。)複製以下代碼,然後單擊編輯菜單上的粘貼爲 HTML,以粘貼文件 authentication
部分中的代碼:
authentication mode=Forms
forms name=.ASPXFORMSDEMO loginUrl=logon.aspx
protection=All path=/ timeout=30 /
/authentication
4.
在 authorization
部分中拒絕匿名用戶的訪問(如下所示):
authorization
deny users =? /
allow users = * /
/authorization
返回頁首
創建示例數據庫表以存儲用戶詳細信息
本節介紹如何創建可存儲用戶名、密碼和用戶角色的示例數據庫。如果要將用戶角色存儲在數據庫中並實現基於角色的安全性,則需要角色列。
1.
在開始菜單上,單擊運行,然後鍵入 notepad 以打開記事本。
2.
突出顯示以下 SQL 腳本代碼,右鍵單擊該代碼,然後單擊複製。在記事本中,單擊編輯菜單上的粘貼以粘貼以下代碼:
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.
將該文件另存爲 Users.sql。
4.
在 Microsoft SQL Server 計算機上,在查詢分析器中打開 Users.sql。在數據庫列表中,單擊pubs,然後運行該腳本。這將創建一個示例用戶表,並使用此示例應用程序填充要使用的 Pubs 數據庫中的該表。
返回頁首
創建 Logon.aspx 頁
1.
將一個新的 Web 窗體添加到名爲 Logon.aspx 的項目中。
2.
在編輯器中打開 Logon.aspx 頁,並切換到 HTML 視圖。
3.
複製以下代碼,然後使用編輯菜單上的粘貼爲 HTML選項將代碼插入到 form 標記之間:
h3
font face=VerdanaLogon Page/font
/h3
table
tr
tdEmail:/td
tdinput id=txtUserName type=text runat=server/td
tdASP:RequiredFieldValidator ControlToValidate=txtUserName
Display=Static ErrorMessage=* runat=server
ID=vUserName //td
/tr
tr
tdPassword:/td
tdinput id=txtUserPass type=password runat=server/td
tdASP:RequiredFieldValidator ControlToValidate=txtUserPass
Display=Static ErrorMessage=* runat=server
ID=vUserPass /
/td
/tr
tr
tdPersistent Cookie:/td
tdASP:CheckBox id=chkPersistCookie runat=server autopostback=false //td
td/td
/tr
/table
input type=submit Value=Logon runat=server ID=cmdLoginp/p
asp:Label id=lblMsg ForeColor=red Font-Name=Verdana Font-Size=10 runat=server /
此 Web 窗體用於向用戶提供登錄窗體,以便他們提供用於登錄到應用程序的用戶名和密碼。
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 ) );
}
4.
可使用兩種方法之一生成窗體身份驗證 Cookie,並將用戶重定向到 cmdLogin_ServerClick
事件中的相應頁。爲兩種情形都提供了示例代碼。可根據需要使用其中的一個。
調用 RedirectFromLoginPage
方法,以便自動生成窗體身份驗證 Cookie,並將用戶重定向到 cmdLogin_ServerClick
事件中的相應頁:
private void cmdLogin_ServerClick(object sender, System.EventArgs e)
{
if (ValidateUser(txtUserName.Value,txtUserPass.Value) )
FormsAuthentication.RedirectFromLoginPage(txtUserName.Value,
chkPersistCookie.Checked);
else
Response.Redirect(logon.aspx, true);
}
生成身份驗證票證,對其進行加密,創建 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);
if (chkPersistCookie.Checked)
ck.Expires=tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);
string strRedirect;
strRedirect = Request[ReturnUrl];
if (strRedirect==null)
strRedirect = default.aspx;
Response.Redirect(strRedirect, true);
}
else
Response.Redirect(logon.aspx, true);
}
5.
確保將以下代碼添加到由 Web 窗體設計器生成的代碼的 InitializeComponent
方法中。
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.
雙擊 SignOut
打開代碼隱藏頁 (Default.aspx.cs),並在 cmdSignOut_ServerClick
事件處理程序中複製以下代碼:
private void cmdSignOut_ServerClick(object sender, System.EventArgs e)
{
FormsAuthentication.SignOut();
Response.Redirect(logon.aspx, true);
}
6.
確保將以下代碼添加到由 Web 窗體設計器生成的代碼的 InitializeComponent
方法中。
this.cmdSignOut.ServerClick += new System.EventHandler(this.cmdSignOut_ServerClick);
7.
保存並編譯項目。現在,您就可以使用該應用程序了。
返回頁首
其他說明
您可能希望將密碼安全地存儲在數據庫中。在將密碼存儲在數據庫或配置文件中之前,可以使用名爲 HashPasswordForStoringInConfigFile
的 FormsAuthentication
類實用工具函數對密碼進行加密。
您可能希望將 SQL 連接信息存儲在配置文件 (Web.config) 中,以便在需要時方便地修改它。
也可以考慮添加代碼,以防***使用不同的密碼組合進行登錄。例如,可以包含一個只允許兩次或三次登錄嘗試的邏輯。如果用戶在嘗試特定次數後無法登錄,您可能希望在數據庫中設置一個標誌以禁止此用戶登錄,直到此用戶通過訪問另外一個頁面或撥打您的支持電話重新啓用其帳戶時爲止。另外,還應根據需要添加相應的錯誤處理代碼。
因爲用戶是基於身份驗證 Cookie 來標識的,所以您可能希望在此應用程序上使用安全套接字層 (SSL),這樣任何人都無法騙取身份驗證 Cookie 和傳輸的任何其他重要信息。
基於窗體的身份驗證要求客戶機在其瀏覽器上接受或啓用 Cookie。
authentication
配置部分的 timeout
參數控制重新生成身份驗證 Cookie 的時間間隔。您可以選擇一個能提供較好性能和安全性的值。
Internet 上的某些中間代理和緩存可能會將包含設置 Cookie標題的 Web 服務器響應緩存起來,然後將其返回給另外一個用戶。因爲基於窗體身份驗證使用 cookie 來驗證用戶身份,所以這可能導致用戶通過接收到由中間代理或緩存提供的本不是要發送給他們的 cookie 而意外(或有意地)模擬另外的用戶。下面這篇文章介紹如何對付這些情形:
263730
Site Server 用戶可能被驗證成錯誤的帳戶
返回頁首
參考
有關如何使用 credentials
部分存儲用戶和密碼來實現基於窗體的簡單身份驗證的更多信息,請參閱以下 GotDotNet ASP.NET 快速入門示例:
基於窗體的身份驗證
http://www.gotdotnet.com/QuickStart/aspplus/default.aspx?url=/quickstart/aspplus/doc/formsauth.aspx
有關如何使用 XML 文件存儲用戶和密碼來實現基於窗體的身份驗證的更多信息,請參閱 .NET Framework 軟件開發工具包 (SDK) 文檔中的以下主題:
使用 XML 用戶文件的窗體身份驗證
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconcookieauthenticationusinganxmlusersfile.asp
有關 ASP.NET Web 應用程序安全性的更多信息,請參閱以下 Microsoft .NET Framework 開發人員指南文檔:
ASP.NET Web 應用程序安全性
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconaspnetwebapplicationsecurity.asp
有關 System.Web.Security
命名空間的更多信息,請參閱以下 Microsoft .NET Framework 參考文檔:
System.Web.Security 命名空間
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemWebSecurity.asp
有關 ASP.NET 配置的更多信息,請參閱以下 Microsoft .NET Framework 開發人員指南文檔:
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 白皮書:
ASP.NET 中的身份驗證:.NET 安全指南
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/authaspdotnet.asp
有關 ASP.NET 的更多常規信息,請訪問以下 MSDN 新聞組:
microsoft.public.dotnet.framework.aspnet
返回頁首
這篇文章中的信息適用於:
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 標準版
Microsoft SQL Server 7.0 標準版
Microsoft SQL Server 2000 64-bit Edition