WCF - Cannot find a token authenticator for X509SecurityToken - c#

I'm trying to call a 3rd party webservice and I've gotten to the point where I can actually see a response from the server in the Service Trace Viewer. However, I keep getting an exception from .NET:
Cannot find a token authenticator for the 'System.IdentityModel.Tokens.X509SecurityToken' token type.
Tokens of that type cannot be accepted according to current security settings.
My app.config looks like this (Thumbprints replaced by placeholders):
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="OteBehavior">
<clientCredentials>
<serviceCertificate>
<authentication certificateValidationMode="None"/>
<defaultCertificate findValue="<ThumbprintPlaceholder1>" x509FindType="FindByThumbprint" storeLocation="CurrentUser" storeName="TrustedPeople"/>
</serviceCertificate>
<clientCertificate findValue="<ThumbprintPlaceholder2>" x509FindType="FindByThumbprint"/>
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<customBinding>
<binding name="MyBinding">
<textMessageEncoding messageVersion="Soap11" />
<security authenticationMode="CertificateOverTransport"
messageSecurityVersion="WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10"
requireSecurityContextCancellation="false"
enableUnsecuredResponse="true"
allowSerializedSigningTokenOnReply="true">
</security>
<httpsTransport maxBufferPoolSize="2147483646" maxBufferSize="2147483646" maxReceivedMessageSize="2147483646" requireClientCertificate="true" />
</binding>
</customBinding>
</bindings>
<client>
<endpoint address="https://example.com:1443/xxx/someService/"
binding="customBinding" bindingConfiguration="MyBinding" behaviorConfiguration="OteBehavior"
contract="ReportGasService.ReportGas" name="ReportGasEndpoint" />
</client>
Now, I've tried everything I could find regarding this exception.
Setting authenticationMode to MutualCertificate: Server responds 404
Setting allowSerializedSigningTokenOnReply: No change
The reponse from the server contains:
<ds:KeyInfo Id="KI-1DE4B371623632132E1468838210413180294">
<wsse:SecurityTokenReference wsu:Id="STR-1DE4B271123632132E1468838710413180295">
<wsse:Reference URI="#X509-1DE4B271523632132E1468833710413180293" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"></wsse:Reference>
</wsse:SecurityTokenReference>
</ds:KeyInfo>
Can I add the x508SecurityToken handler somewhere or otherwise ignore this error (is it safe to do so)
Exception Stack Trace:
Server stack trace:
at System.ServiceModel.Security.ReceiveSecurityHeader.ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver, IList`1 allowedTokenAuthenticators, SecurityTokenAuthenticator& usedTokenAuthenticator)
at System.ServiceModel.Security.ReceiveSecurityHeader.ReadToken(XmlDictionaryReader reader, Int32 position, Byte[] decryptedBuffer, SecurityToken encryptionToken, String idInEncryptedForm, TimeSpan timeout)
at System.ServiceModel.Security.ReceiveSecurityHeader.ExecuteFullPass(XmlDictionaryReader reader)
at System.ServiceModel.Security.StrictModeSecurityHeaderElementInferenceEngine.ExecuteProcessingPasses(ReceiveSecurityHeader securityHeader, XmlDictionaryReader reader)
at System.ServiceModel.Security.ReceiveSecurityHeader.Process(TimeSpan timeout, ChannelBinding channelBinding, ExtendedProtectionPolicy extendedProtectionPolicy)
at System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessageCore(Message& message, TimeSpan timeout)
at System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessage(Message& message, TimeSpan timeout)
at System.ServiceModel.Security.SecurityProtocol.VerifyIncomingMessage(Message& message, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Does the above mean that it is serverside?

I found the solution:
Change authenticationMode="CertificateOverTransport" to authenticationMode="MutualCertificate"
Use MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10
In the generated client, add ProtectionLevel = ProtectionLevel.Sign to the ServiceContractAttribute. This avoids having the body encrypted.
I'm still not all the way through, but I believe it is merely a matter of getting the right certificate from the provider.
For others, here is how I create my proxy:
var binding = new BasicHttpsBinding();
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
var address = new EndpointAddress(new Uri("https://xxx/yyy/someService/"));
binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.Certificate;
var securityElement = SecurityBindingElement.CreateMutualCertificateBindingElement(MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10, true);
securityElement.IncludeTimestamp = true;
var customBinding = new CustomBinding(binding);
customBinding.Elements.Insert(0, securityElement);
var client = new ReportGasClient(customBinding, address);
client.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByThumbprint, "BCC3929F9C115D4BCA1C697E2557B7FC7D6C8C8C");
client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
client.ClientCredentials.ServiceCertificate.SetDefaultCertificate(StoreLocation.CurrentUser, StoreName.TrustedPeople, X509FindType.FindByThumbprint, "87C3B5EE3913937459D2FFBF105ADBD1A578E823");
Please note I set the ValidationMode to None only in the sandbox environment. This should never be used in production.

Your values for findValue attribute are both incorrect. You should be putting the specific thumbprint value for the corresponding client-side certificates in the app.config.
You can view the certificate thumbprint values via the Certificates MMC add-in.
I would also double-check that client-side X509 certificates are required as normally, they are only required for server-side operation.

Related

Error calling WS on ASP.NET: Cannot process the message because the content type application soap xml charset utf 8

I've tried to execute a method of a web service on my console application (c# .Net 4.5.2), but I've received the following error: "(415) Cannot process the message because the content type 'application/xml; charset=utf-8' was not the expected type 'text/xml; charset=utf-8'.."
app.config
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="AnotherBindingWS"
maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647"
maxBufferPoolSize="2147483647" />
</webHttpBinding>
<basicHttpBinding>
<binding name="BasicHttpBinding_IIntegracion"
maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647"
maxBufferPoolSize="2147483647"/>
</basicHttpBinding>
</bindings>
<client>
<endpoint
name="BasicHttpBinding_IIntegracion"
address="http://servicios.cruzdelsur.com/Interfaces_Test/Integracion.svc"
binding="webHttpBinding"
bindingConfiguration="AnotherBindingWS"
contract="WSIntegracionCDS.IIntegracion"
behaviorConfiguration="webhttp"/>
</client>
<services>
<service name="WSIntegracionCDS.IIntegracion">
<endpoint
name="AnotherBindingServiceWS"
address="http://servicios.cruzdelsur.com/Interfaces_Test/Integracion.svc"
binding="webHttpBinding"
bindingConfiguration="AnotherBindingWS"
contract="WSIntegracionCDS.IIntegracion"
behaviorConfiguration="webhttp"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="webhttp">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
Program.cs
IntegracionClient clientWS = new IntegracionClient();
CrearDespachos_Input inputDespachosWS = new CrearDespachos_Input();
List<Despacho> newDespachos = new List<Despacho>();
foreach (var cbte in comprobantesCDS)
{
Despacho itemDespacho = GetNewDespacho(cbte);
newDespachos.Add(itemDespacho);
}
inputDespachosWS.Despachos = newDespachos.ToArray();
//On the following line I receive the exception
CrearDespachos_Output output = clientWS.CrearDespachos(inputDespachosWS);
I attached the exception on execution CrearDespachos method Exception on runtime
ex.StackTrace
Server stack trace:
en System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
en System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
en System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
en System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
en System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
en System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
en System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
en System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
en System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
en ESAIntegracionesService.WSIntegracionCDS.IIntegracion.CrearDespachos(CrearDespachos_Input Input)
en ESAIntegracionesService.WSIntegracionCDS.IntegracionClient.CrearDespachos(CrearDespachos_Input Input) en C:\dev\esa-web\ESAIntegracionesService\Service References\WSIntegracionCDS\Reference.cs:línea 2691
en ESAIntegracionesService.Program.ActualizarComprobantes(String token) en C:\dev\esa-web\ESAIntegracionesService\Program.cs:línea 121
¿Could you help me?
Thanks a lot!

C# consuming soap WS returns Security header error in VerifyIncomingMessage

I have a SoapUI project that has a request with credentials in soap header like this
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:rgw="http://ThirdPartyWebService.wsdl">
<soapenv:Header>
<wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasisopen.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:wsu="http://docs.oasisopen.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsse:UsernameToken wsu:Id="UsernameToken-12346579123456789">
<wsse:Username>username</wsse:Username>
<wsse:Password>password</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>
<soapenv:Body>
.........
</soapenv:Body>
</soapenv:Envelope>
SoapUI project works well and i get the response of this kind:
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<env:Header/>
<env:Body>
<m:ThirdPartyWSMethodResponse xmlns:m="http://gr/gsis/ThirdPartyWS/ThirdPartyWS.wsdl">
<ThirdPartyWSBasic_out>
<m:string1>string 1</m:string1>
<m:date1 xsi:nil="true"/>
<m:string2>string 2</m:string2>
</ThirdPartyWSBasic_out>
<arrayOfThirdPartyWSFirmAct_out>
<m:ThirdPartyWSFirmActUser>
<m:Descr>some free text</m:Descr>
<m:Kind>1</m:Kind>
<m:KindDescr>some string</m:KindDescr>
<m:Code>some code as string</m:Code>
</m:ThirdPartyWSFirmActUser>
</arrayOfThirdPartyWSFirmAct_out>
<pCallSeqId_out>111111111</pCallSeqId_out>
<pErrorRec_out>
<m:errorDescr xsi:nil="true"/>
<m:errorCode xsi:nil="true"/>
</pErrorRec_out>
</m:ThirdPartyWSMethodResponse>
</env:Body>
</env:Envelope>
I'm trying to consume the same soap WS in a C# project with this code (I added it as a Service Reference):
ThirdPartyWSClient client = new ThirdPartyWSClient();
client.ClientCredentials.UserName.UserName = "username";
client.ClientCredentials.UserName.Password = "password";
System.Net.ServicePointManager.ServerCertificateValidationCallback = (senderX, certificate, chain, sslPolicyErrors) => { return true; };
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
ThirdPartyWSInputUser inputBody = new ThirdPartyWSInputUser();
inputBody.parameter1 = "800542811";
ThirdPartyWSBasicUser ThirdPartyWSBasic_out = new ThirdPartyWSBasicUser();
ThirdPartyWSUserArray arrayOfThirdPartyWS_out = new ThirdPartyWSUserArray();
decimal pCallSeqId_out = new decimal();
GenWsErrorUser pErrorRec_out = new GenWsErrorUser();
client.thirdPartyWSMethod(inputBody, ref ThirdPartyWSBasic_out, ref arrayOfThirdPartyWS_out, ref pCallSeqId_out, ref pErrorRec_out);
with bindings:
<bindings>
<basicHttpBinding>
<binding name="ThirdPartyWSPublic">
<security mode="TransportWithMessageCredential" />
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="https://www.ThirdPartyWS/ThirdPartyWSPublicPort"
binding="basicHttpBinding" bindingConfiguration="RgWsPublic"
contract="SoapWebService.ThirdPartyWSPublic" name="ThirdPartyWSPublicPort" />
</client>
And I receive the following error:
Security processor was unable to find a security header in the message. This might be because the message is an unsecured fault or because there is a binding mismatch between the communicating parties. This can occur if the service is configured for security and the client is not using security.
With this stack trace:
Server stack trace:
at System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessageCore(Message& message, TimeSpan timeout)
at System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessage(Message& message, TimeSpan timeout)
at System.ServiceModel.Security.SecurityProtocol.VerifyIncomingMessage(Message& message, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at .................................
The problem is that is cannot verify the incoming message. I used fiddler and found that I get proper response from the WS! The only thing that seemed strange is that my request included a timestamp element in the header and it did not have the wsse: and soapenv: expected tags but was like this:
<s:Envelope
xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<s:Header>
<o:Security s:mustUnderstand="1"
xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<u:Timestamp u:Id="_0">
<u:Created>2020-06-05T13:35:58.208Z</u:Created>
<u:Expires>2020-06-05T13:40:58.208Z</u:Expires>
</u:Timestamp>
<o:UsernameToken u:Id="uuid-11111111111111111111">
<o:Username>username</o:Username>
<o:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">password</o:Password>
</o:UsernameToken>
</o:Security>
</s:Header>
<s:Body>
<ThirdPartyWSPublicMethod>
...
</ThirdPartyWSPublicMethod>
</s:Body>
</s:Envelope>
The web service is a public sector WS and needs authentication thus I cannot provide it. Unfortunately I cannot show the exact requests and responses as they contain sensitive personal data.
I have tried everything I found here and there but couldn't solve this. Any help would be highly appreciated! Thanks
I managed to solve this problem by using a custom binding and disabling timestamp and proxy. Thank you #jdweng for pointing to the correct direction
<customBinding>
<binding name="ThirdPartyWSPublic">
<security authenticationMode="UserNameOverTransport" includeTimestamp="false">
<secureConversationBootstrap />
</security>
<textMessageEncoding messageVersion="Soap11" />
<httpsTransport useDefaultWebProxy="false" requireClientCertificate="false" />
</binding>
</customBinding>

How to dynamically call a net.tcp Web Service

I am trying to call a WCF from my C# desktop app but i get an error. This is my code:
//Client Code
System.ServiceModel.EndpointAddress addressSync = new System.ServiceModel.EndpointAddress("net.tcp://an ip address/Sync2.svc");
Shared.FactorySync = new System.ServiceModel.ChannelFactory<LiteEdition.wsSyncFastest.ISync2Channel>("NetTcpBinding_ISync2", addressSync);
Shared.UpLoadSync = Shared.FactorySync.CreateChannel();
[QUESTION. If I dynamically create a client call to a WCF can I assume i do NOT need to include anything in th app.config file about the bindings?]
//error message on this line:
Shared.UpLoadSync.UploadMotionDynamic2(new byte[1]{0}, 0, 0);
//IS:
The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:00:59.9349963'
.
//My Service:
public void UploadMotionDynamic2(byte[] jpegData, int status, int framePart)
{
DAL dal = new DAL();
try
{
if (jpegData != null)
{
LiveView2.SetNewFrame(status, framePart, jpegData);
}
}
catch (Exception ex)
{
email.SendError("Sync.UploadMotionDynamic:" + ex.ToString(), "");
}
}
//In my Web.Config
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="NetTCPBehaviour">
<serviceTimeouts transactionTimeout="0.00:00:30" />
<serviceDebug includeExceptionDetailInFaults="false" />
<dataContractSerializer maxItemsInObjectGraph="65536" />
<serviceMetadata httpGetEnabled="true" />
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="testme" behaviorConfiguration="NetTCPBehaviour">
<endpoint address="Sync2.svc" binding="netTcpBinding" contract="ISync" name="wsMotionUploader" bindingConfiguration="NetTCPBindingEndPoint">
<!--<security mode="None"></security>-->
</endpoint>
</service>
</services>
<bindings>
<netTcpBinding>
<binding name="NetTCPBindingEndPoint" receiveTimeout="00:15:00" sendTimeout="00:15:00" transferMode="Streamed" closeTimeout="00:02:00" openTimeout="00:02:00"
maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
<readerQuotas maxArrayLength="32768" />
<security mode="None">
<transport clientCredentialType="None" protectionLevel="None" />
<message clientCredentialType="None" />
</security>
</binding>
</netTcpBinding>
</bindings>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
Amended Code:
System.ServiceModel.NetTcpBinding binding = new System.ServiceModel.NetTcpBinding();
System.ServiceModel.EndpointAddress address = new System.ServiceModel.EndpointAddress("http:ip/Sync2");
System.ServiceModel.ChannelFactory<System.ServiceModel.Channels.IRequestChannel> factory =
new System.ServiceModel.ChannelFactory<System.ServiceModel.Channels.IRequestChannel>(binding, address);
var channel = factory.CreateChannel();
channel.Open();
UPDATED TO THIS:
System.ServiceModel.NetTcpBinding binding = new System.ServiceModel.NetTcpBinding();
System.ServiceModel.EndpointAddress address = new System.ServiceModel.EndpointAddress("net.tcp://ip/Sync2");
System.ServiceModel.ChannelFactory<WindowsFormsApplication2.ws.ISync2Channel> factory =
new System.ServiceModel.ChannelFactory<WindowsFormsApplication2.ws.ISync2Channel>(binding, address);
factory.Endpoint.Contract.SessionMode = System.ServiceModel.SessionMode.Allowed;
WindowsFormsApplication2.ws.ISync2Channel channel = factory.CreateChannel();
channel.Open();
But get this error 'Object reference not set to an instance of an object.'
on the .Open() method.
Also, the 'WindowsFormsApplication2.ws.ISync2Channel' is defined because I had already added a reference to the Service. If I had not what would I have
used instead?
///******************new settings:
Client code:
ws.Sync2Client wcf = new ws.Sync2Client("NetTcpBinding_ISync2");
wcf.UploadMotionDynamic2(new byte[1]{1},0,0);
Client App.Config:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_ISync2" />
</basicHttpBinding>
<netTcpBinding>
<binding name="NetTcpBinding_ISync2" />
</netTcpBinding>
</bindings>
<client>
<endpoint address="http://ip/Sync2.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ISync2"
contract="ws.ISync2" name="BasicHttpBinding_ISync2" />
<endpoint address="net.tcp://ip/Sync2.svc" binding="netTcpBinding"
bindingConfiguration="NetTcpBinding_ISync2" contract="ws.ISync2"
name="NetTcpBinding_ISync2">
<identity>
<servicePrincipalName value="host/ip" />
</identity>
</endpoint>
</client>
</system.serviceModel>
Server Web.Config
-->
The error I get is on this line:
wcf.UploadMotionDynamic2(new byte[1]{1},0,0);
The error is:
Object reference not set to an instance of an object.
the stack is:
Server stack trace:
at System.ServiceModel.Channels.SocketConnectionInitiator.Connect(Uri uri, TimeSpan timeout)
at System.ServiceModel.Channels.BufferedConnectionInitiator.Connect(Uri uri, TimeSpan timeout)
at System.ServiceModel.Channels.ConnectionPoolHelper.EstablishConnection(TimeSpan timeout)
at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel channel, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
at System.ServiceModel.Channels.ServiceChannel.EnsureOpened(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at WindowsFormsApplication2.ws.ISync2.UploadMotionDynamic2(Byte[] jpegData, Int32 status, Int32 framePart)
at WindowsFormsApplication2.ws.Sync2Client.UploadMotionDynamic2(Byte[] jpegData, Int32 status, Int32 framePart) in m:\Visual Studio 2013\Projects\WindowsFormsApplication2\WindowsFormsApplication2\Service References\ws\Reference.cs:line 81
at WindowsFormsApplication2.Form1.button1_Click(Object sender, EventArgs e) in m:\Visual Studio 2013\Projects\WindowsFormsApplication2\WindowsFormsApplication2\Form1.cs:line 581
This all works when I use http binding though...
The port 780 is open on my server.
the Net.Tcp.Listener Adaptor is running
Enabled Protocols in IIS has net.tcp
Still no joy
It looks like your using the wrong constructor for your requirements.
When using the ChannelFactory(String, EndpointAddress) constructor, the first parameter stands for the name of your endpoint configuration (in your config file).
Using the ChannelFactory(Binding, EndpointAddress) constructor will fulfill your requirement of passing the configuration programmatically.
Use this constructor when you want to pass the binding and address information programmatically rather than using an application configuration file.
You can use the ChannelFactory class to call the wcf service, in this case you dont need to have endpoints and bindings in configuration file. Everything(endpoints, behaviors) you can create in the c# something like below code
var channelFactory = new ChannelFactory<IService>(new BasicHttpBinding(), "http://myurl:8080/ServiceFirst");
IService client = channelFactory.CreateChannel();
check out this link
http://msdn.microsoft.com/en-us/library/ms734681(v=vs.110).aspx

Binding error (binding mismatch?, security mismatch?) when calling a web service

Please forgive my lack of experience with WCF, but I'm having an issue with it that I am having some difficulty understanding.
Another organization at the company I work at has created a web service for me to consume. I believe I have correctly added a Service Reference to my project using the WSDL they provided. Their web service is based off of an Oracle API that I know very little of, I'm not an Oracle developer.
Here is the code I used to make use of the service reference:
BasicHttpBinding basicHttpBinding = new BasicHttpBinding();
basicHttpBinding.Security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential;
basicHttpBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
EndpointAddress epa = new EndpointAddress("https://MYENDPOINT.URL");
MyServiceReference.SERVICENAME_PortTypeClient port = new MyServiceReference.SERVICENAME_PortTypeClient(basicHttpBinding, epa);
port.ClientCredentials.UserName.UserName = SERVICE_U;
port.ClientCredentials.UserName.Password = SERVICE_P;
SOAHeader header = new SOAHeader();
header.Responsibility = SERVICE_RESPONSIBILITY;
InputParameters2 ip2 = new InputParameters2();
ip2.param1 = "abcd";
ip2.param2 = "1234"
OutputParameters2 output = port.WEB_SERVICE_FUNCTION(header, ip2);
Here the information in my Web.Config file regarding the binding information:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="SERVICENAME_Binding">
<security mode="None" />
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="https://MYENDPOINT.URL"
binding="basicHttpBinding" bindingConfiguration="SERVICENAME_Binding"
contract="MyServiceReference.SERVICENAME_PortType"
name=SERVICENAME_Port" />
</client>
</system.serviceModel>
When the call is made to the service I get the following error:
Security processor was unable to find a security header in the
message. This might be because the message is an unsecured fault or
because there is a binding mismatch between the communicating parties.
This can occur if the service is configured for security and the
client is not using security.
With the following stacktrace:
at System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessageCore(Message& message, TimeSpan timeout)
at System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessage(Message& message, TimeSpan timeout)
at System.ServiceModel.Security.SecurityProtocol.VerifyIncomingMessage(Message& message, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at MyProject.MyServiceReference.SERVICE_NAME_PortType.WEB_SERVICE_FUNCTION(WEB_SERVICE_FUNCTIONRequest request)
at MyProject.MyServiceReference.SERVICE_NAME_PortTypeClient.MyProject.MyServiceReference.SERVICE_NAME_PortType.WEB_SERVICE_FUNCTION(WEB_SERVICE_FUNCTIONRequest request) in c:\MyProject\Service References\MyServiceReference\Reference.cs:line 981
at MyProject.MyServiceReference.SERVICE_NAME_PortTypeClient.WEB_SERVICE_FUNCTION(SOAHeader SOAHeader, InputParameters2 InputParameters) in c:\MyProject\Service References\MyServiceReference\Reference.cs:line 988
at MyProject.MyClass.MyFunction(String inputParam) in c:\MyProject\MyClass.asmx.cs:line 160
After looking at the stack trace, it appears that the verification of the response may be the issue which lead me to believe that it may have to do with a timestamp issue that others have had (ex. http://blog.latamhub.com/?p=78) may be the issue, but when I try to add the includeTimestamp="true" attribute to the security tag in the Web.Config file, VS2012 reports that the includeTimestamp attribute is not allowed. Not quite certain what is going on here or what else to check. Any help or ideas are greatly appreciated.
Thanks.
EDIT (2013-05-30):
Tried the following custom binding with the includeTimestamp set to true and false with no success:
<customBinding>
<binding name="SERVICENAME_Binding">
<security
includeTimestamp="true"
/>
</binding>
</customBinding>

WCF: The service certificate is not provided. Specify a service certificate in ServiceCredentials

I'm trying to create a WCF service that uses the MembershipProvider for authentication. Because it is an internal service I'm currently not interested in applying transport level security (HTTPS) and I want to (for now) do this without a certificate. Besides, this will complicate rolling out the service and I wish to do this at a later point in time. I've built a basic configuration (even without configuring the MembershipProvider, but WCF keeps throwing me the following exception:
The service certificate is not provided. Specify a service certificate
in ServiceCredentials.
Here's my configuration:
<system.serviceModel>
<bindings>
<ws2007HttpBinding>
<binding name="Service1WS2007HttpBindingConfig">
<security mode="Message">
<transport clientCredentialType="None" />
<message clientCredentialType="UserName" />
</security>
</binding>
</ws2007HttpBinding>
</bindings>
<services>
<service name="WcfService1.Service1">
<endpoint address="http://localhost:9800/Service1.svc"
binding="ws2007HttpBinding"
bindingConfiguration="Service1WS2007HttpBindingConfig"
contract="WcfService1.IService1" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="false">
<serviceActivations>
<add relativeAddress="Service1.svc" service="WcfService1.Service1" />
</serviceActivations>
</serviceHostingEnvironment>
</system.serviceModel>
Stacktrace of the exception:
[InvalidOperationException: The service certificate is not provided.
Specify a service certificate in ServiceCredentials. ]
System.ServiceModel.Security.ServiceCredentialsSecurityTokenManager.CreateServerX509TokenProvider()
+12382737 System.ServiceModel.Security.ServiceCredentialsSecurityTokenManager.CreateLocalSecurityTokenProvider(RecipientServiceModelSecurityTokenRequirement
recipientRequirement) +63
System.ServiceModel.Security.ServiceCredentialsSecurityTokenManager.CreateSecurityTokenProvider(SecurityTokenRequirement
requirement) +48
System.ServiceModel.Security.ServiceCredentialsSecurityTokenManager.CreateTlsnegoServerX509TokenProvider(RecipientServiceModelSecurityTokenRequirement
recipientRequirement) +191
System.ServiceModel.Security.ServiceCredentialsSecurityTokenManager.CreateTlsnegoSecurityTokenAuthenticator(RecipientServiceModelSecurityTokenRequirement
recipientRequirement, Boolean requireClientCertificate,
SecurityTokenResolver& sctResolver) +683
System.ServiceModel.Security.ServiceCredentialsSecurityTokenManager.CreateSecurityTokenAuthenticator(SecurityTokenRequirement
tokenRequirement, SecurityTokenResolver& outOfBandTokenResolver)
+12383208 System.ServiceModel.Security.SessionRenewSecurityTokenManager.CreateSecurityTokenAuthenticator(SecurityTokenRequirement
tokenRequirement, SecurityTokenResolver& outOfBandTokenResolver) +81
System.ServiceModel.Security.SymmetricSecurityProtocolFactory.OnOpen(TimeSpan
timeout) +181
System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan
timeout) +21
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) +318
System.ServiceModel.Security.SecurityListenerSettingsLifetimeManager.Open(TimeSpan
timeout) +94
System.ServiceModel.Channels.SecurityChannelListener`1.OnOpen(TimeSpan
timeout) +240
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) +318
System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan
timeout) +72
[InvalidOperationException: The ChannelDispatcher at
'http://localhost:9800/Service1.svc' with contract(s)
'"IssueAndRenewSession"' is unable to open its IChannelListener.]
System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan
timeout) +118
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) +318 System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan
timeout) +111
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) +318
System.ServiceModel.Security.SecuritySessionSecurityTokenAuthenticator.OnOpen(TimeSpan
timeout) +131
System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan
timeout) +21
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) +318
System.ServiceModel.Security.CommunicationObjectSecurityTokenAuthenticator.Open(TimeSpan
timeout) +20
System.ServiceModel.Security.SecuritySessionServerSettings.OnOpen(TimeSpan
timeout) +792
System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan
timeout) +21
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) +318
System.ServiceModel.Security.SecurityListenerSettingsLifetimeManager.Open(TimeSpan
timeout) +148
System.ServiceModel.Channels.SecurityChannelListener`1.OnOpen(TimeSpan
timeout) +240
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) +318
System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan
timeout) +72
[InvalidOperationException: The ChannelDispatcher at
'http://localhost:9800/Service1.svc' with contract(s) '"IService1"' is
unable to open its IChannelListener.]
System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan
timeout) +118
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) +318 System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan
timeout) +111
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) +318
System.ServiceModel.HostingManager.ActivateService(String
normalizedVirtualPath) +206
System.ServiceModel.HostingManager.EnsureServiceAvailable(String
normalizedVirtualPath) +651
[ServiceActivationException: The service '/Service1.svc' cannot be
activated due to an exception during compilation. The exception
message is: The ChannelDispatcher at
'http://localhost:9800/Service1.svc' with contract(s) '"IService1"' is
unable to open its IChannelListener..]
System.Runtime.AsyncResult.End(IAsyncResult result) +688590
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult
result) +190
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.ExecuteSynchronous(HttpApplication
context, String routeServiceVirtualPath, Boolean flowContext, Boolean
ensureWFService) +234
System.ServiceModel.Activation.HttpModule.ProcessRequest(Object
sender, EventArgs e) +359
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+148 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
What is wrong with my configuration and how can I solve this?
You need to sign the service with a certificate. You can do this by adding the following to the configuration:
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="false" />
*<serviceCredentials>
<serviceCertificate findValue="certificatename" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
</serviceCredentials>*
</behavior>
</serviceBehaviors>
Where certificatename is the name of your certificate. To create a certificate you can look here:
Create a self signed certificate
Setting <security mode="None"> and commenting the serviceCertificate tag inside <serviceCredentials> in my Web.config solved the problem for me.
I was having this problem in localhost, so I didn't need these security settings.

Categories

Resources