2011-11-03 45 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;