SharePoint WCF Service with HTTPS and Cert

Frequent Contributor

Hi There,

I create a WCF for SharePoint with HTTPS and Cert. But I am still cannot connect to the WCF Service (in the ISAPI folder). I list out my sample code and web.config. how could I sort it out.?? do you have any idea on it? I got the error message ::

Thanks for your help

"

System.ServiceModel.Security.SecurityNegotiationException
  HResult=0x80131500
  Message=Could not establish trust relationship for the SSL/TLS secure channel with authority 'ext.litwareinc.pri'.
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>
Inner Exception 1:
HttpRequestException: The SSL connection could not be established, see inner exception.
Inner Exception 2:
AuthenticationException: The remote certificate is invalid according to the validation procedure.

"

web.config

<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MyServiceServiceBehavior">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"></serviceMetadata>
          <serviceDebug includeExceptionDetailInFaults="true"></serviceDebug>      
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="jsonBehaviour">
          <webHttp />
          <clientCredentials>  
            <serviceCertificate>  
              <authentication certificateValidationMode="PeerOrChainTrust" />  
            </serviceCertificate>  
          </clientCredentials>
        </behavior>   
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <wsHttpBinding>
        <!--<binding name="BasicHttpEndpointBinding" maxBufferSize="2147483647" maxBufferPoolSize="524288" maxReceivedMessageSize="2147483647">
        </binding>-->
        <binding name="secureHttpBinding" maxBufferSize="2147483647" maxBufferPoolSize="524288" maxReceivedMessageSize="2147483647">
          <!--<security mode="Transport">-->
            <!--<transport clientCredentialType="None"/>-->
          <!--</security>-->
          <security mode="Message">  
            <message clientCredentialType="UserName"/>  
          </security> 
        </binding>
      </wsHttpBinding>
    </bindings>
    <services>
      <service name="wcfSPdocument.Actions" behaviorConfiguration="MyServiceServiceBehavior">
        <!--<endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpEndpointBinding" contract="TecturaWsListItems.v2.IService">
        </endpoint>-->
        <endpoint address=""
                  binding="basicHttpBinding"
                  bindingConfiguration="secureHttpBinding"
                  contract="wcfSPdocument.IActions"/>
        <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange">
        </endpoint>
      </service>
    </services>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true">
    </serviceHostingEnvironment>
  </system.serviceModel>   

Console.cs

 

using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.ServiceModel.Security;

namespace wcfSPdocument.client{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var myBinding = new WSHttpBinding();
            //myBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
            //myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;            myBinding.Security.Mode = SecurityMode.Message;            myBinding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;

            var myEndPoint = new EndpointAddress("https://ext.litwareinc.pri/_vti_bin/wcfSPdocument/Actions.svc");

            /// HTTP WCf
            /// 
            //wcfSPdocument.ActionsClient client = new wcfSPdocument.ActionsClient(myBinding, myEndPoint);

            /// HTTPs WCF
            /// 
            ServiceClient.ActionsClient actionsClient = new ServiceClient.ActionsClient();
                 
            ServicePointManager.ServerCertificateValidationCallback = delegate (object sender1, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
                bool validationResult = true;
                return validationResult;
            };

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(customXertificateValidation);                        
            actionsClient.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine,
    StoreName.My,    X509FindType.FindByThumbprint,
    "6ca3a7298d961286bd34c0523bcdae3d0e119c2f");            actionsClient.ClientCredentials.UserName.UserName = "litwareinc\\Administrator";            actionsClient.ClientCredentials.UserName.Password = "pass@word1";

            //Console.WriteLine("client.state: " + client.State);
            Console.WriteLine("actionsClient state: " + actionsClient.State);

            string filename = @"C:\Users\Administrator\Desktop\docs\deliverables\Deliverable - HTC-Watermarkingand Server Side Viewing - Overview and Configuration.docx";
            //string filename = @"Z:\sharing\docs\disableloopback.txt";

            using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                // Create a byte array of file stream length
                byte[] bytes = System.IO.File.ReadAllBytes(filename);

                //Read block of bytes from stream into the byte array                fs.Read(bytes, 0, System.Convert.ToInt32(fs.Length));

                ServiceClient.DocumentData documentData = new ServiceClient.DocumentData();                documentData.content = bytes;                documentData.filename = Path.GetFileName(filename);                actionsClient.Demonstration(documentData);
                Console.WriteLine("client.state: " + actionsClient.State);

                Console.WriteLine(documentData.filename + " has been uploaded.");

                //Close the File Stream                fs.Close();
            }

            Console.WriteLine("client.state: " + actionsClient.State);

            Console.ReadKey();
        }

        private static bool customXertificateValidation(object sender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error)
        {
            return true;
        }

        /// <summary>
        /// Check if the client is open and then close it.
        /// </summary>
        /// <param name="client">The client to close</param>
        public static void CloseService(wcfSPdocument.ActionsClient client)
        {
            if (client != null && client.State == CommunicationState.Opened)                client.CloseAsync();
        }
    }
}
0 Replies