none
Настройка авторизации на wcf службе на транпортном уровне c использованием самоподписанного сертификата. RRS feed

  • Вопрос

  • Решил настроить авторизацию на  wcf сервисе, размещенном в обычной виндовой службы при помощи самоподписанного сертификата, но увы пока ничего не получается.

    Выполняю следующую последовательность действий:

    Создаю самоподписанный сертификат selfssl /N:cn=hostname /V:3650.

    Помещаю его в личные сертификаты локального компьютера, добавляю его  в доверенные

    корневые центры сертификации локального компьютера.

    Затем меняю конфиг сервиса на следующий:

     <system.serviceModel>
        <bindings>
          <customBinding>
            <binding name="TestMexBinding" openTimeout="00:01:00" sendTimeout="01:00:00" receiveTimeout="01:00:00" closeTimeout="00:01:00">
              <tcpTransport  maxPendingConnections="1000" portSharingEnabled="true" listenBacklog="1000">
                <connectionPoolSettings groupName="default" maxOutboundConnectionsPerEndpoint="1000" />
              </tcpTransport>
            </binding>
          </customBinding>
          <netTcpBinding>
            <binding name="binding" maxConnections="1000"  listenBacklog="1000"  portSharingEnabled="true" openTimeout="00:01:00" sendTimeout="03:00:00" receiveTimeout="03:00:00" closeTimeout="00:01:00" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
              <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
              <reliableSession ordered="true" inactivityTimeout="00:10:00"
                           enabled="false" />
              <security mode="Transport">
                <transport  clientCredentialType="Certificate"></transport>
              </security>
            </binding>
          </netTcpBinding>
        </bindings>
        <!-- This section is optional with the new configuration model
               introduced in .NET Framework 4. -->
        <services>
    
          <service behaviorConfiguration="AutorizationServiceBehavior" name="WebServiceCadTech.AutentificateService">
            <endpoint address="" binding="netTcpBinding" bindingConfiguration="binding" name="NetTcpBindingEndpoint1" contract="WebServiceCadTech.IAutentificateService">
            </endpoint>
            <endpoint address="mex" binding="customBinding" bindingConfiguration="TestMexBinding" contract="IMetadataExchange" />
            <host>
              <baseAddresses>
                <add baseAddress="net.tcp://hostname:443/AutentificateService" />
              </baseAddresses>
            </host>
          </service>
    
        </services>
        <behaviors>
          <serviceBehaviors>
            <behavior name="AutorizationServiceBehavior">
              <serviceCredentials>
                <serviceCertificate findValue="hostname" storeName="My" storeLocation="LocalMachine"
                                    x509FindType="FindByIssuerName" />
              </serviceCredentials>
              <serviceMetadata httpGetEnabled="false" />
              <dataContractSerializer maxItemsInObjectGraph="2147483647" />
              <serviceDebug includeExceptionDetailInFaults="true" />
              <serviceThrottling maxConcurrentCalls="1000" maxConcurrentSessions="1000" maxConcurrentInstances="1000" />
            </behavior>
          </serviceBehaviors>
         
        </behaviors>

    Меняю конфиг svcutil.exe.config на следующий:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
    <system.serviceModel>
    <client>
    <endpoint name="net.tcp" binding="netTcpBinding" behaviorConfiguration="MaxBehavior"  bindingConfiguration="GenericBinding"
    contract="IMetadataExchange" />
    <endpoint name="http" binding="wsHttpBinding" bindingConfiguration="SecureBinding" contract="IMetadataExchange" />
    </client>
    <bindings>
    <netTcpBinding>
    <binding name="GenericBinding"  maxBufferPoolSize="2147483647"
    maxReceivedMessageSize="2147483647" >
    <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
    maxArrayLength="2147483647" maxBytesPerRead="2147483647"
    maxNameTableCharCount="2147483647" />
    <security mode="Transport">
    <transport  clientCredentialType="Certificate"></transport>
    </security>
    </binding>
    </netTcpBinding>
    <wsHttpBinding>
    <binding name="SecureBinding" maxBufferPoolSize="2147483647"
    maxReceivedMessageSize="2147483647" >
    <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
    maxArrayLength="2147483647" maxBytesPerRead="2147483647"
    maxNameTableCharCount="2147483647" />
    <security mode="Message">
    <transport clientCredentialType="Windows" />
    </security>
    </binding>
    </wsHttpBinding>
    </bindings>
       <behaviors>
            <endpointBehaviors>
              <behavior name="MaxBehavior">
              
                <clientCredentials>
                  <clientCertificate findValue="hostname" storeName="My" storeLocation="LocalMachine"
                                    x509FindType="FindByIssuerName"/>
                </clientCredentials>
                <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
              </behavior>
            </endpointBehaviors>
          </behaviors>
    </system.serviceModel>
    </configuration>

    Затем пытаюсь сгенерить прокси классы при помощи svcutil.exe  следующей командой: svcutil net.tcp://hostname:443/AutentificateService/

    и получаю следующую ошибку:

    Microsoft (R) Service Model Metadata Tool
    [Microsoft (R) Windows (R) Communication Foundation, Version 3.0.4506.2152]
    Copyright (c) Microsoft Corporation.  All rights reserved.

    Attempting to download metadata from 'net.tcp://hostname:443/AutentificateServi
    ce/' using WS-Metadata Exchange. This URL does not support DISCO.
    Microsoft (R) Service Model Metadata Tool
    [Microsoft (R) Windows (R) Communication Foundation, Version 3.0.4506.2152]
    Copyright (c) Microsoft Corporation.  All rights reserved.

    Error: Cannot obtain Metadata from net.tcp://hostname:443/AutentificateService/


    If this is a Windows (R) Communication Foundation service to which you have acce
    ss, please check that you have enabled metadata publishing at the specified addr
    ess.  For help enabling metadata publishing, please refer to the MSDN documentat
    ion at http://go.microsoft.com/fwlink/?LinkId=65455.


    WS-Metadata Exchange Error
        URI: net.tcp://hostname:443/AutentificateService/

        Метаданные содержат неразрешимую ссылку: "net.tcp://hostname:443/Autentific
    ateService/".

        <?xml version="1.0" encoding="utf-16"?><Fault xmlns="http://www.w3.org/2003/
    05/soap-envelope"><Code><Value>Sender</Value><Subcode><Value xmlns:a="http://www
    .w3.org/2005/08/addressing">a:ActionNotSupported</Value></Subcode></Code><Reason
    ><Text xml:lang="ru-RU">Сообщение с Action "http://schemas.xmlsoap.org/ws/2004/0
    9/transfer/Get" не может быть обработано на стороне получателя из-за несоответст
    вия ContractFilter на EndpointDispatcher. Возможно, это связано с несоответствие
    м контрактов (несогласованность действий на стороне отправителя и получателя) ил
    и несоответствием привязка/защита на стороне отправителя и получателя.  Убедитес
    ь, что отправитель и получатель имеют один и тот же контракт и одинаковые привяз
    ки (включая требования к защите, например, Message, Transport или None).</Text><
    /Reason></Fault>

    If you would like more help, type "svcutil /?"






    14 июля 2016 г. 8:17

Ответы

  • Вопрос помогло решить видоизменение конфига сервиса следующим образом:

    <system.serviceModel>
        <bindings>
            <netTcpBinding>
            <binding name="binding" maxConnections="1000"  listenBacklog="1000"  portSharingEnabled="true" openTimeout="00:01:00" sendTimeout="03:00:00" receiveTimeout="03:00:00" closeTimeout="00:01:00" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
              <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
               <security mode="Transport">
                <transport protectionLevel="EncryptAndSign"  clientCredentialType="Certificate"></transport>
              </security>
            </binding>
          </netTcpBinding>
        </bindings>
        <!-- This section is optional with the new configuration model
               introduced in .NET Framework 4. -->
        <services>
    
          <service behaviorConfiguration="AutorizationServiceBehavior" name="WebServiceCadTech.AutentificateService">
            <endpoint address=""  binding="netTcpBinding" bindingConfiguration="binding" name="NetTcpBindingEndpoint1" contract="WebServiceCadTech.IAutentificateService">
              
            </endpoint>
            <endpoint
                               address="mex"
                               binding="netTcpBinding"
                               bindingConfiguration="binding"
                               name="NetTcpMetadataPoint"
                               contract="IMetadataExchange" />
           
            <host>
              <baseAddresses>
                <add baseAddress="net.tcp://hostname:443/AutentificateService" />
              </baseAddresses>
            </host>
          </service>
    
        </services>
        <behaviors>
          <serviceBehaviors>
            <behavior name="AutorizationServiceBehavior">
              <serviceCredentials>
                <serviceCertificate findValue="hostname" storeName="My" storeLocation="LocalMachine"
                                    x509FindType="FindByIssuerName" />
               <!--            <clientCertificate>
                  <certificate findValue="hostname" storeName="My" storeLocation="LocalMachine"
                                    x509FindType="FindByIssuerName"/>
                </clientCertificate>  
              -->
    
              </serviceCredentials>
            
              <serviceMetadata httpsGetEnabled="false" httpGetEnabled="false" />
              <dataContractSerializer maxItemsInObjectGraph="2147483647" />
              <serviceDebug includeExceptionDetailInFaults="true" />
              <serviceThrottling maxConcurrentCalls="1000" maxConcurrentSessions="1000" maxConcurrentInstances="1000" />
    
            </behavior>
          </serviceBehaviors>
          <endpointBehaviors>
            <behavior name="behavior">
              <clientCredentials>
                <clientCertificate findValue="hostname" storeName="My" storeLocation="LocalMachine"
                                    x509FindType="FindByIssuerName"/>
              </clientCredentials>
            </behavior>
          </endpointBehaviors>
        </behaviors>
      </system.serviceModel>Также

    Также был изменен файл svcutil.exe.config:

    <system.serviceModel>
    <client>
    <endpoint name="net.tcp" binding="netTcpBinding" behaviorConfiguration="MaxBehavior"  bindingConfiguration="GenericBinding"
    contract="IMetadataExchange" />
    <endpoint name="http" binding="wsHttpBinding" bindingConfiguration="SecureBinding" contract="IMetadataExchange" />
    </client>
    <bindings>
    <netTcpBinding>
    <binding name="GenericBinding"  maxBufferPoolSize="2147483647"
    maxReceivedMessageSize="2147483647" >
    <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
    maxArrayLength="2147483647" maxBytesPerRead="2147483647"
    maxNameTableCharCount="2147483647" />
    <security mode="Transport">
    <transport protectionLevel="EncryptAndSign"  clientCredentialType="Certificate"></transport>
    </security>
    </binding>
    </netTcpBinding>
    <wsHttpBinding>
    <binding name="SecureBinding" maxBufferPoolSize="2147483647"
    maxReceivedMessageSize="2147483647" >
    <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
    maxArrayLength="2147483647" maxBytesPerRead="2147483647"
    maxNameTableCharCount="2147483647" />
    <security mode="Message">
    <transport clientCredentialType="Windows" />
    </security>
    </binding>
    </wsHttpBinding>
    </bindings>
       <behaviors>
            <endpointBehaviors>
              <behavior name="MaxBehavior">
              
                <clientCredentials>
                  <clientCertificate findValue="hostname" storeName="My" storeLocation="LocalMachine"
                                    x509FindType="FindByIssuerName"/>
                </clientCredentials>
                <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
              </behavior>
            </endpointBehaviors>
          </behaviors>
    </system.serviceModel>

    аналогичные изменения необходимо внести в  файл devenv.exe.config если вы хотите чтобы сервис построил прокси классы через команду add reverence в студии


    16 июля 2016 г. 1:50