2012-12-13 288 views
2

什麼是正確的WCF安全實現/配置,可以幫助:WCF安全使用Windows身份驗證

  • 使用現有的Windows帳戶與服務
  • 允許不提供 增加從另一個項目服務引用的驗證憑據
  • 限制,可以調用服務

回答

2

利用現有的用戶Windows帳戶使用服務進行身份驗證

爲此,您應該將綁定配置的transport clientCredentialType屬性設置爲Windows

<bindings> 
    <wsHttpBinding> 
     <binding> 
     <security mode="Message"> 
      <transport clientCredentialType="Windows" /> 
     </security> 
     </binding> 
    </wsHttpBinding> 
</bindings> 

允許添加從另一個項目服務引用的無需提供憑據

要做到這一點,創建一個mex端點爲您服務端點。

<services> 
    <service name="Services.SampleService" behaviorConfiguration="wsDefaultBehavior"> 
     <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> 
    </service> 
</services> 

限制,可以調用服務

這一個用戶是一個涉及多一點。我發現以每個用戶爲基礎確保服務的方式需要定製授權策略。執行授權的類必須實現IAuthorizationPolicy接口。這是我的授權類的完整代碼:

namespace Services.SampleService.Authorization 
{ 
    /// <summary> 
    /// Handles the default authorization for access to the service 
    /// <para>Works in conjunction with the AuthorizedUsersDefault setting</para> 
    /// </summary> 
    public class DefaultAuthorization: IAuthorizationPolicy 
    { 

     string _Id; 

     public DefaultAuthorization() 
     { 
      this._Id = Guid.NewGuid().ToString(); 
     } 

     public bool Evaluate(EvaluationContext evaluationContext, ref object state) 
     { 
      bool isAuthorized = false; 
      try 
      { 
       //get the identity of the authenticated user 
       IIdentity userIdentity = ((IIdentity)((System.Collections.Generic.List<System.Security.Principal.IIdentity>)evaluationContext.Properties["Identities"])[0]); 
       //verify that the user is authorized to access the service 
       isAuthorized = Properties.Settings.Default.AuthorizedUsersDefault.Contains(userIdentity.Name, StringComparison.OrdinalIgnoreCase); 
       if (isAuthorized) 
       { 
        //add the authorized identity to the current context 
        GenericPrincipal principal = new GenericPrincipal(userIdentity, null); 
        evaluationContext.Properties["Principal"] = principal; 
       } 
      } 
      catch (Exception e) 
      { 
       Logging.Log(Severity.Error, "There was an error authorizing a user", e); 
       isAuthorized = false; 
      } 
      return isAuthorized; 
     } 

     public ClaimSet Issuer 
     { 
      get { return ClaimSet.System; } 
     } 

     public string Id 
     { 
      get { return this._Id; } 
     } 
    } 
} 

「魔術師」在Evaluate方法發生。在我的情況下,授權用戶列表維護在名爲AuthorizedUsersDefault的Properties.Settings變量(類型ArrayOfString)中。這樣,我可以維護用戶列表,而無需重新部署整個項目。

,然後用在每個服務的基礎上這一授權策略,設置在ServiceBehaviors節點如下:

<behaviors> 
    <serviceBehaviors> 
     <behavior name="wsDefaultBehavior"> 
     <serviceAuthorization principalPermissionMode="Custom"> 
     <authorizationPolicies> 
      <add policyType="Services.SampleService.Authorization.DefaultAuthorization, MyAssemblyName" /> 
     </authorizationPolicies> 
    </serviceAuthorization> 
     </behavior> 
    </serviceBehaviors> 
</behaviors>