Error during connection to wcf service by ssl RRS feed

  • Question

  • Hello to everybody,

        I've done a wcf service, that is published (I can connect to it by browser and I can see the wsdl) but when I try to consume it by a client program that I've written, I obtain an "An error occurred when verifying security for the message" message. 

    Some detail: consumer and server are on the same machine (so this isn't the case of out-of-sync time between consumer and server), I use a self signed certificate, the service is put in a subsection of a greater solution, and it has a dedicated web.config that overrides the solution one.

    Web.config files are the same both on the service side than on consumer side (I've simply done a copy and paste from service to consumer file). Consumer uses basicHttpBinding and TransportWithMessageCredential connection and, after several attempts, even if I've created a service reference to the service by Visual Studio tool, in the consumer code I specify again both the binding type than the endpoint address.

    As I've already said, the service uses a self signed certificate, and I've implemented a validation class to validate a non trusted certificate.

    When I create the proxy object in my consumer class I don't get any error, I receive it only when I try to consume any method on my service. I've set up the tracelog, but it doesn't seem to show any error, for what I can understand:

    <E2ETraceEvent xmlns="">
    	<System xmlns="">
    		<SubType Name="Information">0</SubType>
    		<TimeCreated SystemTime="2014-10-30T10:41:32.4017455Z" />
    		<Source Name="System.ServiceModel" />
    		<Correlation ActivityID="{43c6480e-e3fe-4916-b3a3-efaa10881db5}" />
    		<Execution ProcessName="w3wp" ProcessID="7004" ThreadID="6" />
    		<Channel />
    				<TraceRecord xmlns="" Severity="Information">
    				<Description>Ricevuta risposta tramite il canale di richiesta</Description>
    				<ExtendedData xmlns="">
    						<Encoder>text/xml; charset=utf-8</Encoder>

    Only using Fiddler I can find an error:

    <span><H1>Errore server nell'applicazione '/PBEWS_Client_Test'.<hr width=100% size=1 color=silver></H1>
                <h2> <i>Errore durante la verifica della sicurezza del messaggio.</i> </h2></span>
                <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
                <b> Descrizione: </b>Eccezione non gestita durante l'esecuzione della richiesta Web corrente. Per ulteriori informazioni sull'errore e sul suo punto di origine nel codice, vedere la traccia dello stack.
                <b> Dettagli eccezione: </b>System.ServiceModel.FaultException: Errore durante la verifica della sicurezza del messaggio.<br><br>
                <b>Errore nel codice sorgente:</b> <br><br>
                <table width=100% bgcolor="#ffffcc">
    Riga 584:        
    Riga 585:        public R...Contracts.PolPolizza RecuperaPolizza(int idPolizza, bool modalita) {
    <font color=red>Riga 586:            return base.Channel.RecuperaPolizza(idPolizza, modalita);
    </font>Riga 587:        }
    Riga 588:        </pre></code>
                <b> File di origine: </b> c:\..\PBEWS_Client_Test\Service References\ServiceReference1\Reference.cs<b> &nbsp;&nbsp; Riga: </b> 586
                <b>Traccia dello stack:</b> <br><br>
                <table width=100% bgcolor="#ffffcc">
    [FaultException: Errore durante la verifica della sicurezza del messaggio.]
       System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +14799942
       System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&amp; msgData, Int32 type) +622
       PBEWS_Client_Test.ServiceReference1.PBEWS.RecuperaPolizza(Int32 idPolizza, Boolean modalita) +0
       PBEWS_Client_Test.ServiceReference1.PBEWSClient.RecuperaPolizza(Int32 idPolizza, Boolean modalita) in c:\Progetti RGI\Rgi.PassBroker\PBEWS_Client_Test\Service References\ServiceReference1\Reference.cs:586
       PBEWS_Client_Test.PBEWS_TestForm.Button1_Click(Object sender, EventArgs e) in c:\Progetti RGI\Rgi.PassBroker\PBEWS_Client_Test\PBEWS_TestForm.aspx.cs:103
       System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +155
       System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3804

    It says "An error occurred when verifying security for the message" and refers to Reference.cs, that is the file that has been created by Visual Studio tool when setting up the service reference. Lines from 577 to 590 contains the following code:

    public PBEWS_Client_Test.ServiceReference1.MRAnaAnagraficaBaseList RicercaAnagrafiche(System.Collections.Generic.List<Rgi.PassBroker.WCF.Contracts.CriterioRicercaWS> criteri) {
                return base.Channel.RicercaAnagrafiche(criteri);
            public System.Threading.Tasks.Task<PBEWS_Client_Test.ServiceReference1.MRAnaAnagraficaBaseList> RicercaAnagraficheAsync(System.Collections.Generic.List<Rgi.PassBroker.WCF.Contracts.CriterioRicercaWS> criteri) {
                return base.Channel.RicercaAnagraficheAsync(criteri);
            public Rgi.PassBroker.WCF.Contracts.PolPolizza RecuperaPolizza(int idPolizza, bool modalita) {
                return base.Channel.RecuperaPolizza(idPolizza, modalita);
            public System.Threading.Tasks.Task<Rgi.PassBroker.WCF.Contracts.PolPolizza> RecuperaPolizzaAsync(int idPolizza, bool modalita) {
                return base.Channel.RecuperaPolizzaAsync(idPolizza, modalita);

    Does anyone have a suggestion that can help me to solve this error?

    Thanx in andvance.

    Tuesday, November 4, 2014 8:17 AM

All replies

  • Hello bancho74,

    Apologies if I misunderstood your question, but I believe you need to override the validation of the self-signed certificate.  You do not need to do this if it is signed by a known authority.

    ServicePointManager.ServerCertificateValidationCallback +=
                new System.Net.Security.RemoteCertificateValidationCallback(CertCheck);
    bool CertCheck(object sender, X509Certificate cert,
            X509Chain chain, System.Net.Security.SslPolicyErrors error)
        return true;

    This post should point you in the right direction:


    Wednesday, November 5, 2014 3:15 AM
  • Hello Jeff,

       Thank you for your answer, but I'm afraid it isn't what I'm looking for: as said in my post I've implemented a validation class, following the guidelines that I've found for this kind of scenario:

    public class PermissiveCertificatePolicy
            string subjectName;
            static PermissiveCertificatePolicy currentPolicy;
            PermissiveCertificatePolicy(string subjectName)
                this.subjectName = subjectName;
                ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(RemoteCertValidate);
            public static void Enact(string subjectName)
                currentPolicy = new PermissiveCertificatePolicy(subjectName);
            bool RemoteCertValidate(object sender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error)
                if (cert.Subject == subjectName)
                    return true;
                return false;

    As you can see, it's the same way you're showing to me.

    Thanks again,



    Wednesday, November 5, 2014 8:21 AM
  • Understand now.  You said you have the save config for both the service and client.  Can you post those as there might be a subtle spelling mistake or something?  I assume that a breakpoint on the server never gets called.

    Also does the RemoteCertValidate ever get called?


    Wednesday, November 5, 2014 6:38 PM
  • Hi Jeff,

         this is the service web.config:

    <?xml version="1.0" encoding="utf-8"?>
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
        <compilation debug="true" targetFramework="4.5" />
        <httpRuntime targetFramework="4.5" />
      <location path="BasicClassicLongTimeout2">
            <allow users="?"/>
        <add key="UrlRgiPasswordUsers" value="https://localhost/.../Password/Services/UserService.svc" />
          <servicePointManager checkCertificateName="false" checkCertificateRevocationList="false" />
          <source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
                     <add name="messages" type="System.Diagnostics.XmlWriterTraceListener" initializeData="c:\Logs\messages.svclog" />
        <messageLogging logEntireMessage="true" logMalformedMessages="false" logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true" maxMessagesToLog="3000" maxSizeOfMessageToLog="2000" />
            <binding name="BasicClassicLongTimeout2" sendTimeout="00:20:00" openTimeout="00:10:00">
              <security mode="TransportWithMessageCredential">
                <message clientCredentialType="UserName" />
                <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
        <services configSource="PBEWS.config" />
            <add type="....WCF.Extensions.SilverlightFaultBehavior,....WCF.Extensions" name="SilverlightFaultBehavior" />
            <add type="....Extensions.SessionBehaviorExtensionElement,....WCF.Extensions" name="sessionBehaviorExtensionElement" />
            <behavior name="PBEWSBehavior">
              <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
              <serviceDebug includeExceptionDetailInFaults="true" />
              <serviceSecurityAudit auditLogLocation="Application" serviceAuthorizationAuditLevel="Failure" messageAuthenticationAuditLevel="Failure" suppressAuditFailure="true" />
              <serviceAuthorization principalPermissionMode="Custom">
                  <add policyType="....Extensions.RgiExternalAuthorizationPolicy2,Rgi.PassBroker.WCF.Extensions" />
                <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="....WCF.ServiceHost.Aspnet.CustomValidationService, Rgi.PassBroker.WCF.ServiceHost.Aspnet" />
                <!--<serviceCertificate findValue="CertificatoPerSviluppo" storeLocation = "LocalMachine" storeName="TrustedPeople" x509FindType="FindBySubjectName"/>-->
            <behavior name="PBEWSBehavior">
                  <!--In questo modo dico a WCF di fidarsi di questo certificato farlocco-->
                  <authentication certificateValidationMode="None" revocationMode="NoCheck" />
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
            <bindingRedirect oldVersion="" newVersion="" />
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
            <parameter value="v11.0" />
          <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
            <directoryBrowse enabled="true" />

    (I've masked the initial part of some istructions: they contain internal path and are not useful for problem comprehension).

    PBEWS.Config contains the endpoint definition:

    <?xml version="1.0" encoding="utf-8" ?>
      <service name="....WCF.Services.PBEWS" behaviorConfiguration="PBEWSBehavior" >
        <endpoint address=""

    Client web.config instead contains:

    <?xml version="1.0" encoding="utf-8"?>
          <compilation debug="true" targetFramework="4.5" />
          <httpRuntime targetFramework="4.5" />
            <source name="System.ServiceModel"
                    switchValue="Information, ActivityTracing"
                <add name="traceListener"
                    initializeData="c:\Logs\Traces.svclog"  />
                    <binding name="BasicHttpBinding_PBEWS">
                      <security mode="TransportWithMessageCredential" />
                <endpoint address=""
                    binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_PBEWS"
                    contract="ServiceReference1.PBEWS" name="BasicHttpBinding_PBEWS" />

    The Remote certificate is called, and returns true, so I think the problem is somewhere in credential validation (if I set Transport instead of TransportWithMessageCredential everything works fine)

    Thank you for your aid.

    Best regards,


    Thursday, November 6, 2014 9:40 AM
  • Hello bancho,

    This is pretty hard to identify just by reading the config but here are a couple things I would try changing from basichttpbinding to wshttpbinding.  I believe basicHttpBinding will only work with transport level security.

    If that does not help then I am at a loss.  I would start with a basic sample project and then start to add your project to it until it breaks.  Painful...

    Here are some references:


    Thursday, November 6, 2014 7:32 PM
  • Hi Jeff,

         Unluckily, I've to merge my service in the active project, so develop as a standalone service is useless for me. I've tested my service with Transport security, and I know that it works, and I've read enough documentation to know that, even if it's better to use wsHttpBinding with TransportWitheMessageCredential, it may be used with basicHttpBinding, too (and for me it's mandatory to use it).

    Thank you for your aid.

    Have a nice week end,


    • Proposed as answer by Mankdng Nef Monday, November 17, 2014 9:40 AM
    Friday, November 7, 2014 3:35 PM
  • Mark it if you solve it.
    Monday, November 17, 2014 9:40 AM