| 開發(fā)人員經(jīng)常編寫需要安全功能的應(yīng)用程序。這些應(yīng)用程序通常需要執(zhí)行一系列不同的安全操作,而且它們還經(jīng)常與不同的基礎(chǔ)安全提供程序(如 Microsoft Active Directory 目錄服務(wù)、授權(quán)管理器、Active Directory 應(yīng)用程序模式 (ADAM) 和自定義數(shù)據(jù)庫等)進行交互。 
 
 驗證應(yīng)用程序塊功能框架如下圖所示: 
 
 幾個基本概念: 
 (1) Ticket:提供對票證的屬性和值的訪問,這些票證用于Forms身份驗證,對用戶進行標識??梢允褂?/span>FormsIdentity 類的 Ticket 屬性訪問當前經(jīng)過身份驗證的用戶的 FormsAuthenticationTicket。通過將當前User 的 Identity 屬性強制轉(zhuǎn)換為類型FormsIdentity,可以訪問當前 FormsIdentity 對象。 
 (2) Token:與當前執(zhí)行線程關(guān)聯(lián)的訪問標記的句柄,用于獲取用戶的Windows帳戶標記。通常,通過調(diào)用非托管代碼(如調(diào)用Win32 API LogonUser 函數(shù))來檢索該帳戶標記。 
 (3) Identity:Identity 封裝有關(guān)正在驗證的用戶或?qū)嶓w的信息。在最基本的級別上,Identity包含名稱和身份驗證類型。名稱可以是用戶名或 Windows 帳戶名,而身份驗證類型可以是所支持的登錄協(xié)議(如 Kerberos V5)或自定義值。.NET Framework 定義了一個 GenericIdentity 對象和一個更專用的WindowsIdentity 對象;前者可用于大多數(shù)自定義登錄方案,而后者可用于在希望應(yīng)用程序依賴于 Windows 身份驗證的情況中。此外,您還可以定義自己的標識類來封裝自定義用戶信息。 
 (4) Principal:Principal 表示代碼運行時所在的安全上下文。實現(xiàn)基于角色的安全性的應(yīng)用程序?qū)⒒谂c主體對象關(guān)聯(lián)的角色來授予權(quán)限。同標識對象類似,.NET Framework 提供 GenericPrincipal 對象和 WindowsPrincipal 對象。您還可以定義自己的自定義主體類。 
 
 下面介紹如何使用Microsoft Enterprise Library 5.0中的驗證應(yīng)用程序模塊. 1. 運行EntLibConfig.exe,選擇Blocks菜單 ,單擊 Add Database Settings . 
 
 
 2. 點擊Authorization Providers 區(qū)塊右上角的加號按鈕, Add Authorization Providers然后點擊 Add Authorization Rule Provider : 
 
 3. 在Authorition Rule Provider面板上右鍵,點擊Add Authorization Rule,我們將新建的Rule名稱設(shè)置為GetAllCollege,表示只有符合驗證表達式的用戶或角色才被允許執(zhí)行獲取所以College操作的權(quán)限: 
 
 
 4. 點擊Rule Expression右邊的…按鈕,彈出驗證表達式編輯對話框: 
 
 5. 在Authorition Rule Provider面板上右鍵,點擊Add Authorization Rule,添加一個憑據(jù)緩存: 
 
 
 6. 點擊File菜單,單擊Save,保存為一個App.config文件,可以先保存到桌面,之后要用到它. 
 7. 創(chuàng)建一個新的控制臺應(yīng)用程序,將App.config添加到程序內(nèi),并加入需要的Dll文件,在此我們要導(dǎo)入的是 Microsoft.Practices.EnterpriseLibrary. Security.dll, Microsoft.Practices.EnterpriseLibrary. Security.Cache.CachingStore.dll并添加需要的引用: 
 
 
 
 8. 測試: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Principal; using Microsoft.Practices.EnterpriseLibrary.Security; namespace test { class Program { staticvoid Main(string[] args) { //創(chuàng)建一個新的用戶 GenericIdentity gID =new GenericIdentity("huang"); IAuthorizationProvider ruleProvider = AuthorizationFactory.GetAuthorizationProvider("Authorization Rule Provider"); //設(shè)置該用戶隸屬于Manage中 IPrincipal principal =new GenericPrincipal(gID, newstring[] { "Manage" }); //驗證 bool authorized = ruleProvider.Authorize(principal, "GetAllCollege"); if (authorized) { Console.WriteLine("驗證成功!"); //保存用戶至緩存中 ISecurityCacheProvider secCache = SecurityCacheFactory.GetSecurityCacheProvider("Security Cache"); //保存,并獲取一個憑證 IToken token = secCache.SaveIdentity(gID); //通過憑證獲取緩存中的用戶 IIdentity savedIdentity = secCache.GetIdentity(token); //打印用戶信息 Console.WriteLine(savedIdentity.Name); } else { Console.WriteLine("登錄失敗!"); } } } } 
 
 9. 運行結(jié)構(gòu): 
 
 | 
|  |