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

时间:2017-06-15 10:26:06

标签: c# rest wcf ssl

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 :

enter image description here

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 : enter image description here

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 :

enter image description here

As you can see when i call this https://localhost/PaymentService.svc my service is available . enter image description here

2 个答案:

答案 0 :(得分:0)

您需要将证书安装为受信任的来源。

  1. 使用管理员权限打开命令提示符,键入“mmc”并按Enter键将打开Microsoft管理控制台。
  2. 从菜单转到文件&gt;添加/删除管理单元,选择“证书”并单击“添加”
  3. 选择计算机帐户,然后单击下一步,选择本地计算机,然后单击完成。
  4. 转到证书(本地计算机)&gt;个人&gt;证书
  5. 从菜单转到操作&gt;所有任务&gt;导入
  6. 在“证书导入向导”中单击“下一步”,提供证书文件的路径,输入密码(如果有),然后单击“下一步”,“下一步”和“完成”。
  7. 现在,您将返回Microsoft管理控制台,单击“受信任的根证书颁发机构”,选择“证书”,“操作”&gt;所有任务&gt;导入并按照步骤6进行操作。
  8. 此外,URL中使用的主机名应与证书上的名称相匹配。确保您使用的URL和证书的“颁发给”字段上的URL相同。

答案 1 :(得分:0)

要消除此错误,请使用与证书部分“颁发给”完全相同的机器名称。例如,如果您打开证书,那么您将看到已发布到属性,哪个应该是您的计算机名称。如果您的计算机是域的一部分,那么计算机名称就像..等等,所以如果您在浏览器中打开它将是您的计算机的完全限定名称,那么您将不会收到该错误。 所以我只需按https://union-pc58.union.com/Service1.svc

这样的域名来调用我的服务

只需点击此链接

即可

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

相关问题