簡體   English   中英

在WCF服務中使用NetworkCredential

[英]Using NetworkCredential in WCF services

我有一個WCF服務,該服務使用Windows身份驗證查看服務合同,並且服務中的特定方法配置為僅由特定用戶UserX訪問。

[PrincipalPermission(SecurityAction.Demand,Name="xxx\\UserA")]

在客戶端,我需要訪問上述服務方法。 如果我使用的是Web參考->我添加以下內容

client = new WebRefLocal.Service1();
client.Credentials = new System.Net.NetworkCredential("UserA", "xxxxxx", "test");

但是以上內容無法在WCF服務參考中實現,因為客戶端憑據是只讀的。 實現上述目標的最佳方法之一是模擬https://msdn.microsoft.com/en-us/library/ff649252.aspx

我的問題是

  1. 為什么在WCF中將ClientCredentials設置為只讀?
  2. 網絡憑據如何工作? 他們將在客戶端或服務器端對Windows登錄進行身份驗證嗎?
  3. 在沒有模擬的情況下,還有什么方法可以在WCF中實現上述目標?

我已經做了類似的事情-希望對您有所幫助:

 var credentials = new ClientCredentials();
credentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Delegation;
credentials.Windows.ClientCredential = new System.Net.NetworkCredential("UserA", "xxxxxx", "test");

client.Endpoint.Behaviors.Remove<ClientCredentials>();
client.Endpoint.Behaviors.Add(credentials);

與具有以下安全設置的BasicHttpBinding一起使用:

  <security mode="TransportCredentialOnly">
    <transport clientCredentialType="Windows" proxyCredentialType="Windows" />
  </security>

您可以使用的一種方法是在調用WCF服務時使用ChannelFactory

以下代碼來自我的一個MVC projects, hence it has some ModelState的驗證代碼,我相信您可以根據自己的需要進行修改。

protected R ExecuteServiceMethod<I, R>(Func<I, R> serviceCall) {
    R result = default(R);
    ChannelFactory<I> factory = CreateChannelFactory<I>();
    try {
        I manager = factory.CreateChannel();
        result = serviceCall.Invoke(manager);
    } catch (FaultException<ValidationFaultException> faultException) {
        faultException.Detail.ValidationErrors.ToList().ForEach(e => ModelState.AddModelError("", e));
    } finally {
        if (factory.State != CommunicationState.Faulted) factory.Close();
    }
    return result;
}

private ChannelFactory<I> CreateChannelFactory<I>() {
   UserAuthentication user = GetCurrentUserAuthentication();

   ChannelFactory<I> factory = new ChannelFactory<I>("Manager");

   if (IsAuthenticated) {
       factory.Credentials.UserName.UserName = user.UserName;
       factory.Credentials.UserName.Password = user.Password;
   }

   BindingElementCollection elements = factory.Endpoint.Binding.CreateBindingElements();
   factory.Endpoint.Binding = new CustomBinding(elements);
   SetDataContractSerializerBehavior(factory.Endpoint.Contract);

   return factory;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM