[c#] WCF gives an unsecured or incorrectly secured fault error

I am trying to consume a remote svc web service. I created the proxy class using svcutil.exe, and after that I've added that class to my console application, but it yields an error:

An unsecured error or incorrectly secured fault was received from the other party. See the inner fault exception for the fault code and detail.

System.ServiceModel.FaultException: An error occurred when verifying security for the message

I didn't create the WCF side, it's a remote svc. Please help.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="EloquaDataTransferService" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Mtom" textEncoding="utf-8" transferMode="Buffered"
                    useDefaultWebProxy="true">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <security mode="TransportWithMessageCredential">
                        <transport clientCredentialType="None" proxyCredentialType="None"
                            realm="" />
                        <message clientCredentialType="UserName" algorithmSuite="Default" />
                    </security>
                </binding>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="https://secure.eloqua.com/API/1.2/DataTransferService.svc"
                binding="basicHttpBinding" bindingConfiguration="EloquaDataTransferService"
                contract="DataTransferService" name="EloquaDataTransferService" />
        </client>
    </system.serviceModel>
</configuration>

This is my app.config file. I am providing the username and password in my consoleApp.cs file using obj.ServiceCredentials.UserName.UserName="xxxxxx" and .Password="xxxXx"

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
   <system.serviceModel>
      <bindings>
         <basicHttpBinding>
            <binding name="EloquaDataTransferService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Mtom" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
               <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
               <security mode="TransportWithMessageCredential">
                  <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
                  <message clientCredentialType="UserName" algorithmSuite="Default" />
               </security>
            </binding>
         </basicHttpBinding>
      </bindings>
      <client>
         <endpoint address="https://secure.eloqua.com/API/1.2/DataTransferService.svc" binding="basicHttpBinding" bindingConfiguration="EloquaDataTransferService" contract="DataTransferService" name="EloquaDataTransferService" />
      </client>
   </system.serviceModel>
</configuration>

This question is related to c# wcf

The answer is


In my case I was using certificates for authentication with certificateValidationMode set to "PeerTrust" and I had forgotten to install the client certificate in windows store (LocalMachine\TrustedPeople) to make it accepted by the server.


I was getting this error due to the BasicHttpBinding not sending a compatible messageVersion to the service i was calling. My solution was to use a custom binding like below

 <bindings>
  <customBinding>
    <binding name="Soap11UserNameOverTransport" openTimeout="00:01:00" receiveTimeout="00:1:00" >
      <security authenticationMode="UserNameOverTransport">
      </security>          
      <textMessageEncoding messageVersion="Soap11WSAddressing10" writeEncoding="utf-8" />
      <httpsTransport></httpsTransport>
    </binding>
  </customBinding>      
</bindings>

In my case the server time was not correct. So I changed the server Datetime settings to Set time automatically and it resolved the issue.


I had to change the SecurityMode to Message (WSHttpBinding), before it worked. i.e.

_wcf = new ServiceRequestClient(new WSHttpBinding(SecurityMode.Message),                     
       new EndpointAddress(_wcfRequestServerAddress));

This is a very obscure fault that WCF services throw. The issue is that WCF is unable to verify the security of the message that was passed to the service.

This is almost always because of a server time skew. The remote server and the client's system time must be within (typically) 10 minutes of each other. If they are not, security validation will fail.

I'd call eloqua.com and find out what their server time is, and compare that to your server time.


In my case, when I changed the wshttpbinding protocol from https to http it started working.


Same this problem i am facing my client application is WinForms application C# 4.0

When i read the solution here, i checked Date & Time of client computer, but that was right and current time was showing, but still i was facing these problem.

After some work-around i found that wrong time zone has selected, i am in India and time zone was of Canada, the host server is located in Kuwait.

I found that system converts time to universal time.

When i changed the time zone to India's time zone, the problem was soled.


If you are passing user credential from client (As per below code block), then it should match with the username/password on server. otherwise you will get this error.

FYI, in my case I am using "basicHTTPAuthentication" with "TransportWithMessageCredential" security mode. And the WCF service is hosted in IIS on https.

var service = new TestService();

service.ClientCredentials.UserName.UserName = "InvalidUser";
service.ClientCredentials.UserName.Password = "InvalidPass";

Hope this will help to someone... :)


In my case, there are two problems that will throw this exception.

Note that, my environment uses Single Sign On (or STS if you prefer) to authenticate a user through ASP.NET MVC site. MVC site in turn makes a service call to my service endpoint by passing bearer token which it requested from STS server with Bootstrap token previously. The error I got was when I made a service call from MVC site.

  1. The WCF service wasn't configured as a relying party in my SSO (or STS if you prefer).

  2. Service's configuration wasn't configured properly. Particularly on audienceUris node of system.identityModel. It must exactly match the service endpoint url.

    <system.identityModel>
        <identityConfiguration>
            <audienceUris>
                <add value="https://localhost/IdpExample.YService/YService.svc" />
            </audienceUris>
            ....
        </identityConfiguration>
    </system.identityModel>
    

Just for the sake of sharing... I had a rare case that got me scratching the back of my head for a few minutes. Even tho the time skew solution was very accurate, and I had that problem solved before, this time was different. I was on a new Win8.1 machine which I remember having a timezone issue and I had manually adjusted the time. Well, I kept getting the error, despite the time displayed in both server and client had only a diference in seconds. What I did is activate "summer saving option" (note that I am indeed under summer saving time, but had the time setup manually) in "date and time setup" then went to the internet time section and refreshed... the time in my pc kept exactly the same, but the error dissapeared.

Hope this is useful to anybody!


Although your problem was solved with one of the above solutions, for the benefit of others, here's another option.

You also can get this exception when incorrect credentials are passed to a basic endpoint (SOAP 1.1) that uses username message credentials as you are. For example, if you are calling the service from code and do something like this:

var service = new TestService();

service.ClientCredentials.UserName.UserName = "InvalidUser";
service.ClientCredentials.UserName.Password = "InvalidPass";

This is different from a WSHTTP endpoint (SOAP 1.2) that throws an AccessDeniedException when invalid credentials are passed through. I personally find the message contained herein a little misleading (it certainly cost me a few minutes the first time I encountered it for this reason) but the underlying cause was clear once I consulted the WCF Diagnostic Trace Logs.


I've also had this problem from a service reference that was out of date, even with the server & client on the same machine. Running 'Update Service Reference' will generally fix it if this is the issue.


In my case, it was a setting on the IIS application pool.

Select the application pool --> Advanced Settings --> Set 'Enable 32 Bit Applications' to True.

Then recycle the application pool.


Try changing your security mode to "transport".

You have a mismatch between the security tag and the transport tag.


You have obviously a problem with the WCF security subsystem. What binding are you using? What authentication? Encryption? Signing? Do you have to cross domain boundaries?

A bit of goggling further reveals that others are experiencing this error if the clocks of client and server are out of sync (more than about five minutes) because some security schemata rely on synchronized clocks.


For what it's worth - I also had this error and found it was caused by the connection string in the web services web.config being set to connect to the wrong machine.


Try with this:

catch (System.Reflection.TargetInvocationException e1)  
      String excType   
      excType = e1.InnerException.GetType().ToString()  
      choose case excType  
                case "System.ServiceModel.FaultException"  
                          System.ServiceModel.FaultException e2  
                          e2 = e1.InnerException  
                          System.ServiceModel.Channels.MessageFault fault  
                          fault = e2.CreateMessageFault()  
                          ls_message = "Class: uo_bcfeWS, Method: registraUnilateral ~r~n" + "Exception(1): " + fault.Reason.ToString()   
                          if (fault.HasDetail) then  
                                    System.Xml.XmlReader reader  
                                    reader = fault.GetReaderAtDetailContents()  
                                    ls_message += " " + reader.Value  
                                    do while reader.Read()  
                                              ls_message += reader.Value  
                                    loop  
                          end if  
                case "System.Text.DecoderFallbackException"  
                          System.Text.DecoderFallbackException e3  
                          e3 = e1.InnerException  
                          ls_message = "Class: uo_bcfeWS, Method: registraUnilateral ~r~n" + "Exception(1): " + e3.Message   
                case else  
                          ls_message = "Class: uo_bcfeWS, Method: registraUnilateral ~r~n" + "Exception(1): " + e1.Message  
      end choose  
      MessageBox ( "Error", ls_message )  
      //logError(ls_message)  
      return false  

_x000D_
_x000D_
<wsHttpBinding>_x000D_
        <binding name="ISG_Binding_Configuration" bypassProxyOnLocal="true" useDefaultWebProxy="false" hostNameComparisonMode="WeakWildcard" sendTimeout="00:30:00" receiveTimeout="00:30:00" maxReceivedMessageSize="2147483647" maxBufferPoolSize="2147483647">_x000D_
          <readerQuotas maxArrayLength="2147483647" maxStringContentLength="2147483647" />_x000D_
          <security mode="None">_x000D_
            <message establishSecurityContext="false" clientCredentialType="UserName"/>_x000D_
          </security>_x000D_
        </binding>_x000D_
      </wsHttpBinding>
_x000D_
_x000D_
_x000D_


Make sure your SendTimeout hasn't elapsed after opening the client.


In my case, I was getting this error on the same machine, in my test client-server application. But this problem was resolved by "Update Service Reference".

  • Tushar G. Walavalkar

Mostly this exception happens when there is some errors in the server, the most common one is a wrong configuration of the authentication database, or authentication. In my case there was different clock synchronization make sure both client and server have same settings

Click on Time at your Right-Bottom side -> "Change date time settings..." -> "Internet Time" tab -> Change Settings... -> check the "Synchronise with an internet time server" option if it is unchecked -> from server dropdown select "times.windows.com" -> Update Now -> OK