Аутентификация WCF с поддержкой токенов через не HTTP-транспорт - PullRequest
1 голос
/ 09 сентября 2011

Я следовал руководству, найденному здесь http://weblogs.asp.net/cibrax/archive/2008/03/26/authenticating-users-with-supporting-tokens-in-wcf-binding-extension.aspx, для создания политики безопасности, отвечающей моим потребностям.У меня это работает, как описано в статье, используя HTTP-транспорт WCF.

Однако мне не удалось настроить customBinding для работы с транспортом, отличным от Http, таким как обычный WCF TCP.Я получаю сообщение об ошибке:

Binding 'CustomBinding' doesn't support creating any channel types. This often
indicates that the BindingElements in a CustomBinding have been stacked incorrectly 
or in the wrong order. A Transport is required at the bottom of the stack. The 
recommended order for BindingElements is: TransactionFlow, ReliableSession, 
Security, CompositeDuplex, OneWay, StreamSecurity, MessageEncoding, Transport.

У кого-нибудь есть предложения по настройке customBinding для использования транспорта TCP?

Пример привязки со страницы:

<customBinding>
  <binding name="MutualCertificateBinding">
    <security authenticationMode="MutualCertificate"/>
    <httpTransport/>
  </binding>
</customBinding>

Я нашел этот пост в блоге http://blog.ploeh.dk/2009/06/22/CustomTokensOverNonHTTPTransports.aspx о возможном решении, но в данном случае он не работает, поскольку он использует безопасность сообщений, а потоковый транспорт не работает с безопасностью сообщений.Затем, если я изменяю на «буферизованный», я получаю ту же ошибку.

Для полноты: проблема, которую я решаю, заключается в передаче имени пользователя вошедшего в систему пользователя с веб-сайта ASP.NET MVC в службу WCFкоторый должен знать пользователя, чтобы возвращать только данные, специфичные для этого пользователя.

РЕДАКТИРОВАТЬ: Как запрос, моя конфигурация привязки: Рабочая Конфигурация клиента Http:

<system.serviceModel>
    <bindings>
        <customBinding>
            <binding name="MutualCertificate">
                <security authenticationMode="MutualCertificate" />
                <httpTransport/>
            </binding>
        </customBinding>
        <trustedWeb>
            <binding name="MyTrustedWeb"
                     bindingReference="MutualCertificate" />
        </trustedWeb>
    </bindings>
    <client>
        <endpoint address="http://localhost:8732/Design_Time_Addresses/DataServices/MyDataService"
                  binding="trustedWeb"
                  bindingConfiguration="MyTrustedWeb"
                  behaviorConfiguration="ClientBehavior"
                  contract = "IMyDataService">
            <identity>
                <dns value="MyDns" />
            </identity>
        </endpoint>
    </client>
    <behaviors>
        <endpointBehaviors>
            <behavior name="ClientBehavior">
                <clientCredentials>
                    <clientCertificate findValue="CN=ClientCert"
                                       storeLocation="LocalMachine"
                                       storeName="My"
                                       x509FindType="FindBySubjectDistinguishedName" />
                    <serviceCertificate>
                        <defaultCertificate findValue="CN=ServiceCert"
                                            storeLocation="LocalMachine"
                                            storeName="My"
                                            x509FindType="FindBySubjectDistinguishedName" />
                        <authentication revocationMode="NoCheck"
                                        certificateValidationMode="None" />
                    </serviceCertificate>
                </clientCredentials>
            </behavior>
        </endpointBehaviors>
    </behaviors>
    <extensions>
        <bindingExtensions>
            <add name="trustedWeb"
                 type="TrustedWebExtension.TrustedBindingCollectionElement, TrustedWebExtension"/>
        </bindingExtensions>
    </extensions>
</system.serviceModel>

Рабочая Конфигурация службы Http:

<system.serviceModel>
<bindings>
    <customBinding>
        <binding name="MutualCertificate">
            <security authenticationMode="MutualCertificate" />
            <httpTransport />
        </binding>
    </customBinding>
    <trustedWeb>
        <binding name="MyTrustedWeb"
                 bindingReference="MutualCertificate" />
    </trustedWeb>
</bindings>
<services>
    <!-- Use this service when testing with authentication, as you will need a custom client with username / password ability. -->
  <service behaviorConfiguration="MyDataServiceBehavior"
    name="MyDataService">
      <endpoint address="/DataServices/MyDataService"
                binding="trustedWeb"
                bindingConfiguration="MyTrustedWeb"
                contract="IMyDataService" >
          <identity>
              <dns value="MyDns"/>
          </identity>
      </endpoint>

      <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
    <host>
      <baseAddresses>
          <add baseAddress="http://localhost:8732/Design_Time_Addresses" />
          <add baseAddress="net.tcp://localhost:30000"/>
      </baseAddresses>
    </host>
  </service>
</services>
<behaviors>
  <serviceBehaviors>      
    <behavior name="MyDataServiceBehavior">
      <!-- To avoid disclosing metadata information, 
      set the value below to false and remove the metadata endpoint above before deployment -->
      <serviceMetadata httpGetEnabled="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="True" />
        <serviceCredentials>
            <!-- <userNameAuthentication userNamePasswordValidationMode="MembershipProvider"
                                    membershipProviderName="SqlMembershipProvider" /> -->
            <serviceCertificate findValue="CN=ServiceCert"
                                storeLocation="LocalMachine"
                                storeName="My"
                                x509FindType="FindBySubjectDistinguishedName" />
            <clientCertificate>
                <!-- <authentication certificateValidationMode="None" /> -->
                <authentication revocationMode="NoCheck"
                                certificateValidationMode="PeerTrust" />
            </clientCertificate>
            <userNameAuthentication userNamePasswordValidationMode="Custom"
                                    customUserNamePasswordValidatorType="TrustedWebExtension.UsernameBlankPasswordValidator, TrustedWebExtension"/>
        </serviceCredentials>
    </behavior>
  </serviceBehaviors>
</behaviors>
  <extensions>
      <bindingExtensions>
          <add name="trustedWeb"
               type="TrustedWebExtension.TrustedBindingCollectionElement, TrustedWebExtension"/>
      </bindingExtensions>
  </extensions>

Не работает Конфигурация на стороне службы TCP: Измените <httpTransport/> на <tcpTransport /> и попробуйте запустить службу.Хост службы Wcf выдает ошибку выше.Я пробовал несколько вариантов этой темы, указав больше значений для стека транспорта и customBinding, но не смог заставить что-либо работать.

...