Wcf Отдых с проблемой UserNamePasswordValidator

Я пытаюсь добавить UserNamePasswordValidator в проект "Приложение службы отдыха WCF" с Visual Studio 2010, проблема в том, что он никогда не входит в класс UserNamePasswordValidator, работает ли UserNamePasswordValidator с Wcf Rest?

Добрый совет..

ниже мой класс обслуживания:

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using System.Security.Principal;


namespace MyService
{
    // Start the service and browse to http://<machine_name>:<port>/Service1/help to view the service's generated help page
    // NOTE: By default, a new instance of the service is created for each call; change the InstanceContextMode to Single if you want
    // a single instance of the service to process all calls.   
    [ServiceContract(Namespace = "MyService")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    // NOTE: If the service is renamed, remember to update the global.asax.cs file
    public class Helo
    {
        [WebGet(UriTemplate = "{name}")]
        public string GetName(string name)
        {
            // TODO: Replace the current implementation to return a collection of SampleItem instances
            return "Hello " + name;
        }

        public class CustomUserNameValidator : System.IdentityModel.Selectors.UserNamePasswordValidator
        {
            // This method validates users. It allows in two users, test1 and test2 
            // with passwords 1tset and 2tset respectively.
            // This code is for illustration purposes only and 
            // MUST NOT be used in a production environment because it is NOT secure.   
            public override void Validate(string userName, string password)
            {
                if (null == userName || null == password)
                {
                    throw new ArgumentNullException();
                }

                if (!(userName == "test1" && password == "1tset") && !(userName == "test2" && password == "2tset"))
                {
                    throw new FaultException("Unknown Username or Incorrect Password");
                }

                throw new FaultException("Unknown Username or Incorrect Password");
            }
        }
    }
}

ниже находится web.config:

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

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

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </modules>
  </system.webServer>

  <system.serviceModel>

    <services>
      <service name="MyService.Hello" behaviorConfiguration="HelloServiceBehavior">
        <!-- use base address provided by host, provide one endpoint -->
        <endpoint address="username" binding="wsHttpBinding" bindingConfiguration="Binding1" contract="MyService.Hello"/>
      </service>
    </services>

    <bindings>
      <wsHttpBinding>
        <!-- Username binding -->
        <binding name="Binding1">
          <security mode="Message">
            <message clientCredentialType="UserName"/>
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>

    <behaviors>
      <serviceBehaviors>
        <behavior name="HelloServiceBehavior">
          <serviceCredentials>
            <!-- 
            The serviceCredentials behavior allows one to specify a custom validator for username/password combinations.                  
            -->
            <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="MyService.Hello+CustomUserNameValidator, MyService"/>
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>


    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <!--<standardEndpoints>
      <webHttpEndpoint>
        --><!-- 
            Configure the WCF REST service base address via the global.asax.cs file and the default endpoint 
            via the attributes on the <standardEndpoint> element below
        --><!--
        <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
      </webHttpEndpoint>
    </standardEndpoints>-->
  </system.serviceModel>

</configuration>

2 ответа

Вы должны иметь webHttpBinding и установить clientCredentialType в basic, который будет использовать ваш производный UserNamePasswordValidator. Если у вас настроен HTTPS, тогда, конечно, измените режим безопасности на Transport:

        <bindings>
        <webHttpBinding>
            <binding name="RestBindingConfiguration">
                <security mode="None">
                    <transport clientCredentialType="Basic"/>
                </security>
            </binding>
        </webHttpBinding>
        </bindings>

С другой стороны, FaultExceptions - это только SOAP, так что имейте это в виду, если вам нужно вызвать исключение для клиента. В зависимости от исключительного случая, MessageSecurityException может иметь смысл.

Я не уверен, что вы все еще ищете ответ на этот вопрос, но если вы...

Настройка аутентификации на WCF REST более чем сложна. Похоже, вы смоделировали свою попытку непосредственно из MSDN, амирит? Мне тоже не повезло с этим. Вы можете попытаться смоделировать после этого решения, которое является довольно простым примером базовой аутентификации. Но мое предложение, потому что оно мне очень помогло, - смоделировать ваш проект после WcfRestContrib. В проект уже встроена не только базовая аутентификация, но и многие другие функции, которые вы в конечном итоге обнаружите, что хотите. Вы можете включить аутентификацию для всей службы или только для конечной точки по конечной точке.

Надеюсь, это поможет.

Другие вопросы по тегам