Невозможно получить доступ к метаданным службы WCF, когда введен пользовательский валидатор - PullRequest
0 голосов
/ 02 февраля 2019

У меня есть веб-служба (использующая wsHttpBinding и SSL), разработанная в Visual Studio 2017. Всякий раз, когда я представляю следующую строку, веб-служба просто отказывает, и она переходит в состояние «сбой».

<authentication certificateValidationMode="Custom" customCertificateValidatorType="SampleProject.SampleService.AuthenticationCertificateValidator, SampleProject.SampleService"/>

Сообщение об ошибке при попытке «Добавить ссылку на службу» на стороне клиента я получаю следующую ошибку:

There was an error downloading 'https://localhost/SampleService/service'.
The request failed with HTTP status 404: Not Found.
Metadata contains a reference that cannot be resolved: 
'https://localhost/SampleService/service'.
There was no endpoint listening at https://localhost/SampleService/service 
that could accept the message. This is often caused by an incorrect address 
or SOAP action. See InnerException, if present, for more details.
The remote server returned an error: (404) Not Found.
If the service is defined in the current solution, try building the 
solution and adding the service reference again.

Вот код, относящийся к валидатору.

public class AuthenticationCertificateValidator : X509CertificateValidator
{
   string allowedIssuerName;

public AuthenticationCertificateValidator(string allowedIssuerName)
{
    if (allowedIssuerName == null)
    {
        throw new ArgumentNullException("allowedIssuerName");
    }

    this.allowedIssuerName = allowedIssuerName;
}

public override void Validate(X509Certificate2 certificate)
{
    // Check that there is a certificate.
    if (certificate == null)
    {
        throw new ArgumentNullException("certificate");
    }

    // Check that the certificate issuer matches the configured issuer.
    if (allowedIssuerName != certificate.IssuerName.Name)
    {
        throw new SecurityTokenValidationException
          ("Certificate was not issued by a trusted issuer");
    }
}
}

Однако сервис работает нормально, когда у меня включена только строка «ChainTrust», как показано ниже:

<!--certificateValidationMode="Custom" 
       customCertificateValidatorType
       ="SampleProject.SampleService.AuthenticationCertificateValidator, 
        SampleProject.SampleService"/>-->
<authentication certificateValidationMode="ChainTrust" />

В идеале я хочу, чтобы мой сервис и клиент использовали ChainTrust, а также использовали пользовательскиекласс валидатора, если это возможно?

Поэтому, что я делаю неправильно в отношении конфигурации?Я что-то упустил из файла конфигурации?

Вот полная конфигурация службы:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
  <services>
  <service name="SampleProject.SampleService.SampleService" 
    behaviorConfiguration="SampleService_Behavior">
    <endpoint
      address="https://localhost/SampleService/service"
      binding="wsHttpBinding"
      bindingConfiguration="SampleService_Binding"
      contract="SampleProject.SampleService.ISampleService" />
   <endpoint
      address="https://localhost/SampleService/service/mex"
      binding="mexHttpsBinding"
      contract="IMetadataExchange" />

  </service>
</services>

<bindings>
  <wsHttpBinding>
    <binding name="SampleService_Binding"
             maxReceivedMessageSize="2147483647"
             maxBufferPoolSize="2147483647" >
      <readerQuotas
        maxDepth="2147483647"
        maxStringContentLength="2147483646"
        maxArrayLength="2147483647"
        maxBytesPerRead="2147483647"
        maxNameTableCharCount="2147483647"/>
      <security mode="TransportWithMessageCredential">
        <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
        <message clientCredentialType="Certificate"  negotiateServiceCredential="true" 
        algorithmSuite="Default" establishSecurityContext="true" />
      </security>
    </binding>
  </wsHttpBinding>
</bindings>

<behaviors>
  <serviceBehaviors>
    <behavior name="SampleService_Behavior">
      <!--Service metadata is needed for when you have an mex endpoint exposed-->
      <serviceMetadata httpsGetEnabled="true" httpsGetUrl="https://localhost/SampleService/service/mex"/>
      <serviceDebug includeExceptionDetailInFaults="True"/>
      <!--The serviceCredentials behavior defines a service certificate
                    which is used by the service to authenticate itself to its
                    clients and to provide message protection. -->
      <serviceCredentials>
        <serviceCertificate
          findValue="SampleServer"
          storeLocation="LocalMachine"
          storeName="My"
          x509FindType="FindBySubjectName" />
        <clientCertificate>
          <!--<authentication certificateValidationMode="ChainTrust" />-->
          <authentication 
          certificateValidationMode="Custom" 
       customCertificateValidatorType
       ="SampleProject.SampleService.AuthenticationCertificateValidator, 
        SampleProject.SampleService"/>
        </clientCertificate>
      </serviceCredentials>
     </behavior>
    </serviceBehaviors>

     <endpointBehaviors>
        <behavior name="webBehaviour">
        <webHttp/>
     </behavior>
    </endpointBehaviors>
   </behaviors>
  </system.serviceModel>
 </configuration>

, если кто-то может мне помочь, это будет очень признательно.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...