建立一個有登入頁的 Web 應用程式
此過程建立一個新的 ASP.NET Web 應用程式。此應用程式將包含兩個頁;一個是只允許經過身分識別驗證的使用者訪問的預設頁,另一個是用於收集使用者憑證的登入頁。
要建立一個有登入頁的 Web 應用程式,請執行下列操作:
1.啟動 Visual Studio .NET 並建立一個名為 test 的新 Visual C# ASP.NET Web 應用程式。
2.將 WebForm1.aspx 重新命名為 Logon.aspx。
3.將下列控制項添加到 Logon.aspx 來建立登入表單。 1protected System.Web.UI.WebControls.TextBox txtUserName;
2protected System.Web.UI.WebControls.TextBox txtPassword;
3protected System.Web.UI.WebControls.Button Button1;
在方案總管中,然後單擊 Add Web Form,輸入 default.aspx 作為新表單的名稱,然後單擊 Open.
配置 Web 應用程式進行 Forms 身分識別驗證
要通過編輯應用程式的 Web.config 檔案來配置應用程式進行 Forms 身分識別驗證,請執行下列操作:
1.使用方案總管開啟 Web.config。
2.定位到 <authentication> 元素並將 mode 屬性更改為 Forms。
3.將下列 <forms> 元素作為 <authentication> 元素的子項目進行添加,並設定 loginUrl、name、timeout 和 path 屬性,如下所示:
<authentication mode="Forms">
<forms loginUrl="logon.aspx" name="AuthCookie" timeout="60" path="/">
</forms>
</authentication>
4.將下列 <authorization> 元素添加到 <authentication> 元素下。執行這一步的目的是只允許經過身分識別驗證的使用者訪問應用程式。前面建立的 <authentication> 元素的 loginUrl 屬性將未經過身分識別驗證的請求重新導向到 Logon.aspx 頁。
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
為經過身分識別驗證的使用者產生身分識別驗證票
此過程編寫代碼來為經過身分識別驗證的使用者產生身分識別驗證票。身分識別驗證票是由 ASP.NET FormsAuthenticationModule 使用的一種 cookie身份認證代碼通常涉及到根據自訂資料庫或 Active Directory 尋找所提供的使用者名稱和密碼。
要為經過身分識別驗證的使用者產生身分識別驗證票,請執行下列操作:
1開啟 Logon.aspx.cs 檔案並將下列 using 語句添加到位於檔案頂部的現有 using 語句下:using System.Web.Security ;
2.將下列私人 Helper 方法添加到名為 IsAuthenticated 的 WebForm1 類中,此類用於驗證使用者名稱和密碼來對使用者進行身分識別驗證。此代碼假定所有使用者名稱和密碼組合都是有效。 private bool IsAuthenticated( string username, string password )
{
return true;
}
3.添加下列名為 GetRoles 的私人 Helper 方法,此方法用於獲得使用者所屬的角色的集合1private string GetRoles( string username, string password )
2{
3return "Senior Manager|Manager|Employee";
4}
4.在 Designer 模式下顯示 Logon.aspx 表單並雙擊 Logon 按鈕建立一個單擊事件處理常式。
5.添加一個對 IsAuthenticated 方法的調用,提供通過登入表單捕獲的使用者名稱和密碼。將傳回值賦給一個 bool 類型的變數,此變數指出使用者是否已經過身分識別驗證。bool isAuthenticated = IsAuthenticated( txtUserName.Text, txtPassword.Text );
6.如果使用者已經過身分識別驗證,則添加對 GetRoles 方法的調用來獲得使用者的角色列表。if (isAuthenticated == true )
{
string roles = GetRoles( txtUserName.Text, txtPassword.Text );
7.建立一個包含使用者名稱、截止時間和使用者所屬的角色列表的新表單身分識別驗證票。注意,身分識別驗證票的使用者資料屬性用於儲存使用者的角色列表。還要注意,雖然票 /cookie 是否是永久性的取決於您採用的應用程式方案,但下列代碼會建立一個非永久性票FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1, // version
txtUserName.Text, // user name
DateTime.Now, // creation
DateTime.Now.AddMinutes(60),// Expiration
false, // Persistent
roles );
8.添加代碼來建立票的加密字串表示形式,並將其作為資料存放區在 HttpCookie 對象中。string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName,
encryptedTicket);
9.將此 cookie 添加到返回給使用者瀏覽器的 cookie 集合中。
10.將使用者重新導向到最初請求的頁Response.Cookies.Add(authCookie);
//userName 已驗證的使用者的名稱。這不必映射到 Windows 帳戶。
//createPersistentCookie 指定是否應當發出持久性 Cookie(跨瀏覽器會話儲存的 Cookie,Cookie 路徑預設為“/”。
Response.Redirect( FormsAuthentication.GetRedirectUrl(txtUserName.Text,false ));
構造 GenericPrincipal 和 FormsIdentity 對象
此過程實現了一個應用程式身分識別驗證事件處理常式,並根據身分識別驗證票中包含的資訊構造了 GenericPrincipal 和 FormsIdentity 對象。
要構造 GenericPrincipal 和 FormsIdentity 對象,請執行下列操作:
1.從方案總管中,開啟 global.asax。
2.切換到程式碼檢視並將下列 using 語句添加到檔案頂部:
3.定位到 Application_AuthenticateRequest 事件處理常式並添加下列代碼,以從隨請求傳遞的 cookie 集合中獲得表單身分識別驗證 cookie
4.添加下列代碼以從表單身分識別驗證 cookie 中提取和解密身分識別驗證票。
5.添加下列代碼,以便解析出使用者在最初對使用者進行身分識別驗證時附加到票上的管道分隔的角色名稱列表
6.添加下列代碼來建立一個 FormsIdentity 對象和一個 GenericPrincipal 對象。前一個對象從票名稱獲得使用者名稱,後一個對象將此標識與使用者角色列表包含在一起。string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if(null == authCookie)
{
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch(Exception ex)
{
return;
}
if (null == authTicket)
{
return;
}
string[] roles = authTicket.UserData.Split(new char[]{'|'});
FormsIdentity id = new FormsIdentity( authTicket );
GenericPrincipal principal = new GenericPrincipal(id, roles);
Context.User = principal;
測試應用程式
此過程將代碼添加到 default.aspx 頁以顯示已附加到當前 HttpContext 對象的 GenericPrincipal 對象中的資訊,目的是確認此對象是否已正確構造且分配給當前的 Web 請求。然後,可以產生並測試此應用程式。
要測試應用程式,請執行下列操作:
1.在方案總管中,雙擊 default.aspx。
2.雙擊 default.aspx Web Form來顯示頁載入事件處理常式。
3.滾動到檔案頂部並將下列 using 語句添加到現有 using 語句下。
4.返回到頁載入事件處理常式並添加下列代碼,以顯示附加到與當前 Web 請求關聯的 GenericPrincipal 的標識名稱
5.添加下列代碼以測試當前經過身分識別驗證的標識的角色成員關係。
6.在方案總管中,按右鍵 default.aspx,然後單擊 Set As Start Page。
7.在 Build 菜單上,單擊 Build Solution。消除任何建置錯誤。
8.按 Ctrl+F5 運行此應用程式。由於 default.aspx 被配置為啟動頁,所以這是最初請求的頁。
9.當您被重新導向到登入頁時(因為最初您沒有身分識別驗證票),輸入使用者名稱和密碼(可隨意輸入),然後單擊 Logon。
10.確認您被重新導向到 default.aspx 且顯示了使用者標識和正確的角色詳細資料。使用者應為 Senior Manager、Manager 和 Employee 角色的成員,但不是 Sales 角色的成員。 using System.Security.Principal;
private void Page_Load(object sender, System.EventArgs e)
{
IPrincipal p = HttpContext.Current.User;
Response.Write( "Authenticated Identity is: " +p.Identity.Name );
Response.Write( "<p>" );
if ( p.IsInRole("Senior Manager") )
Response.Write( "User is in Senior Manager role<p>" );
else
Response.Write( "User is not in Senior Manager role<p>" );
if ( p.IsInRole("Manager") )
Response.Write( "User is in Manager role<p>" );
else
Response.Write( "User is not in Manager role<p>" );
if ( p.IsInRole("Employee") )
Response.Write( "User is in Employee role<p>" );
else
Response.Write( "User is not in Employee role<p>" );
if ( p.IsInRole("Sales") )
Response.Write( "User is in Sales role<p>" );
else
Response.Write( "User is not in Sales role<p>" );
}