Служба WCF - пользовательская аутентификация не работает

Я пытаюсь настроить аутентификацию на своем веб-сервисе, однако после настройки класса проверки, наследуемого от UserNamePasswordValidator, служба по-прежнему позволяет клиенту работать без имени пользователя или пароля.

Веб-сервис

Imports System.IdentityModel.Selectors

Public Class Authentication
    Inherits UserNamePasswordValidator

        Public Overrides Sub Validate(ByVal userName As String, ByVal password As String)
            If Nothing = userName OrElse Nothing = password Then
                Throw New ArgumentNullException()
            End If

            If Not (userName = "1" AndAlso password = "2") Then
                ' This throws an informative fault to the client.
                Throw New FaultException("Unknown Username or Incorrect Password")
                ' When you do not want to throw an infomative fault to the client,
                ' throw the following exception.
                ' Throw New SecurityTokenException("Unknown Username or Incorrect Password")
            End If

        End Sub

    End Class

Web.config

<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>

    <bindings>
      <basicHttpBinding>
        <binding name="Binding1">
          <security mode="Message">
            <message clientCredentialType="UserName" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>

    <services>
      <service name="Webservice.Service1" behaviorConfiguration="ServiceBehavior">
              <endpoint binding="basicHttpBinding" contract="Webservice.IService1"
              behaviorConfiguration="webHttp"/>
      </service> 
    </services>

    <behaviors>
      <serviceBehaviors>

        <behavior name="ServiceBehavior">
          <serviceCredentials>
            <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="Webservice.Authentication, Webservice" />
          </serviceCredentials>
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>


        <behavior>
          <!-- 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="false"/>
        </behavior>
      </serviceBehaviors>

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

    </behaviors>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

Сторона клиента

Dim client As Webservice.Service1Client = New Webservice.Service1Client()

'I was expecting this call to error as no username or password was produced

return client.getData(Data)

Есть ли что-то, что мне не хватает?

Спасибо


person user3428422    schedule 24.08.2015    source источник


Ответы (1)


Вам потребуется больше настроек, чтобы заставить его работать.

Но чтобы получить ошибку, вам нужно использовать bindingConfiguration.

Поэтому измените конфигурацию конечной точки на это:

<services>
    <service name="Webservice.Service1" behaviorConfiguration="ServiceBehavior">
            <endpoint binding="basicHttpBinding" contract="Webservice.IService1"
            bindingConfiguration="Binding1"/>
    </service> 
</services>

Затем вы начнете получать ошибки, которые, надеюсь, помогут вам создать правильную конфигурацию.

person Juan M. Elosegui    schedule 24.08.2015
comment
Спасибо, так что код, который я сделал, и ваше исправление выше все равно не будут делать то, что я хочу? - person user3428422; 24.08.2015
comment
Да, я знаю. Теперь вы получаете сообщение об ошибке, в котором говорится, что вам нужно выбрать безопасность Transport или TransportWithMessageCredential для учетных данных UserName. Так что нужно изменить это. - person Juan M. Elosegui; 24.08.2015
comment
Нет, я по-прежнему не получаю ошибок, он даже не попадает в метод Validate - person user3428422; 24.08.2015
comment
после использования конфигурации привязки вы можете просмотреть URL-адрес службы ????? (localhost:[port]/Service1.svc) - person Juan M. Elosegui; 24.08.2015
comment
Да, я все еще могу использовать сервис через тестовый клиент WCF и через мой клиент - между прочим, это SOAP - person user3428422; 24.08.2015