简体   繁体   中英

could not establish secure channel for ssl/tls with authority wcf C# wcf rest service

I create a client application that get data from my rest wcf service as you can see :

 Uri reqUri = new Uri("https://localhost/paymentservice.svc/listpayment");



            WebRequest req = WebRequest.Create(reqUri);

            req.PreAuthenticate = true;

            NetworkCredential credential = new NetworkCredential("test", "test123");

            req.Credentials = credential;

            WebResponse resp = req.GetResponse();


            DataContractSerializer data = new DataContractSerializer(typeof(string));
            var res = data.ReadObject(resp.GetResponseStream());

            Console.WriteLine(res);

            Console.ReadLine();

I create a certificate in iis as you can se :

在此处输入图片说明

And upload my published file on it . But when i call my client i get this error :

An unhandled exception of type 'System.Net.WebException' occurred in System.dll

Additional information: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel

Here is my service webconfig

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
    <authentication mode="None" />
  </system.web>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="secureHttpBinding">
          <security mode="Message">
            <message clientCredentialType="UserName" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <services>
      <service name="Payment.Application.ServiceImplement.PaymentService" behaviorConfiguration="customBehaviour">
        <endpoint address=""
                  binding="webHttpBinding"
                  contract="Payment.Domain.Service.IPaymentService"
                  behaviorConfiguration="web"/>

      </service>
      <service name="Payment.Infrustructure.RepositoryImplement.PaymentRepository" behaviorConfiguration="customBehaviour" >
        <endpoint address=""
                  binding="webHttpBinding"
                  contract="Payment.Domain.Repository.IPaymentRepository"
                  behaviorConfiguration="web"/>
      </service>

    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior  name="customBehaviour">
          <serviceCredentials>
            <userNameAuthentication userNamePasswordValidationMode="Custom"
                                    customUserNamePasswordValidatorType="Payment.Service.UserAuthentication,Payment.Service"/>
          </serviceCredentials>

          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>

        <behavior name="web">
          <webHttp/>

        </behavior>
      </endpointBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Methods" value="GET, POST,PUT,DELETE" />
      </customHeaders>
    </httpProtocol>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true" />
    <validation validateIntegratedModeConfiguration="false" />
  </system.webServer>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=.;initial catalog=SymfaDB;user id= sa ;password=12345;" providerName="System.Data.SqlClient" />
    <!--<add name="DefaultConnection" connectionString="Data Source=92.50.12.222,1433;initial catalog=ParkingDB;user id= sa ;password=123qweQWE@;" providerName="System.Data.SqlClient" />-->
  </connectionStrings>
</configuration>

When irun the project in visual studio and call this url http://localhost:4428/PaymentService.svc/listpayment I get the data as you can see : 在此处输入图片说明

But when i upload the publish file into iis and call this url https://localhost/PaymentService.svc/listpayment as you can see i get this error :

在此处输入图片说明

As you can see when i call this https://localhost/PaymentService.svc my service is available . 在此处输入图片说明

You need to install the certificate as trusted source.

  1. Open a command prompt with admin rights, type "mmc" and press enter which will open Microsoft Management Console.
  2. From Menu go to File > Add/Remove Snap-In, select Certificates and Click Add
  3. Select Computer Account and click Next, select Local Computer and click Finish.
  4. Go to Certificates (Local Computer) > Personal > Certificates
  5. From the Menu go to Action > All Tasks > Import
  6. Click Next in the Certificate Import Wizard, Provide the path to the certificate file, enter the password if any then click Next, Next and Finish.
  7. Now you will be back to Microsoft Management Console, click on Trusted Root Certification Authorities, select Certificates, Action > All Tasks > Import and follow the step 6.

Also the hostname used in the URL should match the name that's on certificate. Make sure the URL you're using and the URL on the 'Issued to' field of the certificate are the same.

To get rid of this error use the machine name exactly same as your certificate section “Issued to” says. For example, if you open your certificate then you'll see issued to property and which should be your Machine name. If your machine is part of a domain then machine name would be like .. etc, so if you open it in your browser will fully qualified name of your machine then you won't be getting that error. So i just call my service by domain like https://union-pc58.union.com/Service1.svc

Just follow this link

http://www.c-sharpcorner.com/UploadFile/vendettamit/create-secure-wcf-rest-api-with-custom-basic-authentication/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM