2011-11-03 32 views
0

我有一些使用WCF服務的代碼。該服務由基本身份驗證保護,所以在創建客戶端,我用下面的代碼:當我運行從一個控制檯應用程序的代碼從Windows服務調用WCF安全異常

BasicHttpBinding httpBinding = new BasicHttpBinding(); 
    httpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly; 
    httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; 
    httpBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None; 
    httpBinding.Security.Transport.Realm = service_realm; 

    EndpointAddress address = new EndpointAddress(service_address); 

    Service.ServiceClient client = new Service.ServiceClient(httpBinding, address); 

    client.ClientCredentials.UserName.UserName = service_username; 
    client.ClientCredentials.UserName.Password = service_password; 

工作正常。但是當我從Windows服務運行相同的代碼時,正在拋出MessageSecurityException,告訴我我的請求未經授權。出於某種原因,它似乎使用當前的Windows帳戶進行身份驗證,因爲我自己的帳戶有權訪問該服務。但我不希望它,我希望它使用存儲的憑據。我在這裏錯過了什麼?

回答

0

WCF basicHttpBinding不支持明文憑證;原因是因爲你想在傳輸綁定中傳遞證書的時刻,WCF需要底層傳輸是一個安全傳輸,例如SSL。

爲了讓您的代碼正常工作,您需要通過https或使用證書或加密來使用服務。

+0

這可能是這樣,但這用於當我有一個正常的app.config時工作。改變的是我現在通過編程方式創建了綁定,這似乎是導致問題的原因。我認爲你的聲明對於wsHttpBinding是正確的,但不是basicHttpBinding。 – Jasper

0

好像使用這個配置是固定的:

_httpBinding =新basicHttpBinding的();

_httpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly; _httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; _httpBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;

_httpBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName; _httpBinding.Security.Message.AlgorithmSuite = SecurityAlgorithmSuite.Default;

_httpBinding.AllowCookies = false; _httpBinding.BypassProxyOnLocal = false; _httpBinding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; _httpBinding.MessageEncoding = WSMessageEncoding.Text; _httpBinding.TextEncoding = Encoding.UTF8; _httpBinding.TransferMode = TransferMode.Buffered; _httpBinding.UseDefaultWebProxy = false; Service.ServiceClient client = new Service.ServiceClient(_httpBinding,_address);

client.ClientCredentials.UserName.UserName = service_username; client.ClientCredentials.UserName.Password = service_password;