2011-02-15 30 views

回答

2

模擬的目的是將服務的訪問擴展到可能不受限制的資源。它通過考慮請求者的權利來做到這一點。模擬使服務在必須確定是否允許訪問特定資源時承擔請求者的安全上下文。

實現模擬的最簡單方法是聲明性地在服務的方法上。 OperationBehavior屬性包含一個名爲Impersonation的屬性。該屬性可以設置爲「必需」或「允許」。

[OperationBehavior(Impersonation = ImpersonationOption.Allowed)] 
public bool Update() 
{ 
return true; 
} 

如果模擬屬性設置爲允許,客戶端憑證可以流動到服務。如果將模擬設置爲必需,則該服務必須承擔客戶端的憑據。

有些時候並非所有的方法都可能需要模仿。例如,只有在訪問文件時才需要模擬。爲了實現這一點,可以通過使用WindowsImpersonationContext類來強制實施模擬。

要開始,您必須檢索與當前請求關聯的Windows標識。這可通過ServiceSecurityContext.Current對象獲得。如果WindowsIdentity屬性不爲空(記住模擬需要Windows身份),則可以在身份上調用Impersonate方法。下面的代碼演示了這種方法:

WindowsIdentity callerIdentity = 
    ServiceSecurityContext.Current.WindowsIdentity; 
    if (callerIdentity == null) 
    throw new InvalidOperationException(
    "The caller cannot be mapped to a WindowsIdentity"); 
    using (WindowsImpersonationContext context = callerIdentity.Impersonate()) 
    { 
     // Access a file as the caller. 
    } 

證明迄今上的方法,通過方法的基礎操作兩個模擬技術。也可以爲服務中的所有方法啓用模擬。您可以通過將ServiceAuthorization行爲上的ImpersonateCallerForAllOperations屬性設置爲true來執行此操作。你可以這樣做,如下面的代碼示例所示:

ServiceHost serviceHost = new ServiceHost(typeof(TestService)); 
ServiceAuthorizationBehavior behavior = 
serviceHost.Description.Behaviors.Find<ServiceAuthorizationBehavior>(); 
behavior.ImpersonateCallerForAllOperations = true; 
+0

優點/缺點? – WhoIsNinja 2011-02-15 16:08:42