開發人員經常編寫需要安全功能的應用程式。這些應用程式通常需要執行一系列不同的安全操作,而且它們還經常與不同的基礎安全提供程式(如 Microsoft Active Directory 目錄服務、授權管理器、Active Directory 應用程式模式 (ADAM) 和自定義資料庫等)進行互動。
安全應用程式塊通過收集開發人員必須執行的許多最常見的安全任務,來簡化開發人員的工作。每個任務都以一緻的方式處理,從特定的安全提供程式中抽象出應用
程式代碼并使用最佳做法。您甚至可以通過更改配置來更改基礎提供程式,而無需更改基礎應用程式代碼。
驗證應用程式塊功能架構如下圖所示:

幾個基本概念:
(1) Ticket:提供對票證的屬性和值的通路,這些票證用于Forms身份驗證,對使用者進行辨別。可以使用FormsIdentity 類的 Ticket 屬性通路目前經過身份驗證的使用者的 FormsAuthenticationTicket。通過将目前User 的 Identity 屬性強制轉換為類型
FormsIdentity,可以通路目前 FormsIdentity 對象。
(2) Token:與目前執行線程關聯的通路标記的句柄,用于擷取使用者的Windows帳戶标記。通常,通過調用非托管代碼(如調用
Win32 API LogonUser 函數)來檢索該帳戶标記。
(3) Identity:Identity 封裝有關正在驗證的使用者或實體的資訊。在最基本的級别上,Identity包含名稱和身份驗證類型。名稱可以是使用者名或 Windows 帳戶名,而身份驗證類型可以是所支援的登入協定(如 Kerberos V5)或自定義值。.NET Framework 定義了一個 GenericIdentity 對象和一個更專用的
WindowsIdentity 對象;前者可用于大多數自定義登入方案,而後者可用于在希望應用程式依賴于 Windows 身份驗證的情況中。此外,您還可以定義自己的辨別類來封裝自定義使用者資訊。
(4) Principal:Principal 表示代碼運作時所在的安全上下文。實作基于角色的安全性的應用程式将基于與主體對象關聯的角色來授予權限。同辨別對象類似,.NET Framework 提供 GenericPrincipal 對象和 WindowsPrincipal 對象。您還可以定義自己的自定義主體類。
下面介紹如何使用Microsoft Enterprise Library 5.0中的驗證應用程式子產品.
1. 運作EntLibConfig.exe,選擇Blocks菜單 ,單擊 Add Database Settings
.
2.
點選Authorization
Providers 區塊右上角的加号按鈕, Add
Authorization Providers然後點選 Add Authorization Rule Provider :
3.
在Authorition Rule Provider面闆上右鍵,點選Add Authorization Rule,我們将建立的Rule名稱設定為GetAllCollege,表示隻有符合驗證表達式的使用者或角色才被允許執行擷取是以College操作的權限:
4.
點選Rule Expression右邊的…按鈕,彈出驗證表達式編輯對話框:
5.
在Authorition Rule Provider面闆上右鍵,點選Add Authorization Rule,添加一個憑據緩存:
6. 點選
File菜單,單擊
Save,儲存為一個App.config檔案,可以先儲存到桌面,之後要用到它.
7. 建立一個新的控制台應用程式,将App.config添加到程式内,并加入需要的Dll檔案,在此我們要導入的是 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)
//建立一個新的使用者
GenericIdentity gID =new GenericIdentity("huang");
IAuthorizationProvider ruleProvider = AuthorizationFactory.GetAuthorizationProvider("Authorization Rule Provider");
//設定該使用者隸屬于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.
運作結構:
OK,寫完收工,睡覺咯,選修課終于上完了,但還要交一篇論文,是關于"哥本哈根氣候大會"的,請問哪位朋友幫copy一篇過來呀?哈哈~~