WCF - не могу получить Identity.UserName внутри службы - PullRequest
0 голосов
/ 01 декабря 2010

Я пытаюсь создать приложение WP7, которое должно взаимодействовать со службой WCF.
То, что я хочу, это передать имя пользователя / пароль и увидеть его в службе WCF.

        Service1Client proxy = new Service1Client();
        proxy.ClientCredentials.UserName.UserName= "abc@email.com";
        proxy.ClientCredentials.UserName.Password = "abc";

Код, который мы пытались использовать для получения аутентифицированного имени (но вместо этого мы получили идентификатор Windows - MyPc \ MyLogin)

HttpContext.Current.User.Identity.Name

Вот клиентский конфиг

<configuration>
<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name="BasicHttpBinding_IService1" maxBufferSize="2147483647"
                maxReceivedMessageSize="2147483647">
                <!--<security mode="None" />-->
              <security mode="TransportCredentialOnly">
                <!--<transport clientCredentialType="Basic" />-->                   
              </security>
            </binding>
        </basicHttpBinding>
    </bindings>
    <client>
        <endpoint address="http://localhost:45148/Service1.svc" binding="basicHttpBinding"
            bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IService1"
            name="BasicHttpBinding_IService1" />
    </client>
</system.serviceModel>

А вот серверная конфигурация

        <?xml version="1.0"?>
        <configuration>
           <system.web>
            <compilation debug="true" targetFramework="4.0" />
          </system.web>
          <system.serviceModel>
            <behaviors>
              <serviceBehaviors >
                <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="true"/>
                  <serviceCredentials>
                    <userNameAuthentication userNamePasswordValidationMode="Custom"
                     customUserNamePasswordValidatorType="WP7Service.WpfCustomValidator, WP7Service" />
                  </serviceCredentials>
                </behavior>
              </serviceBehaviors>
            </behaviors>
            <bindings>
              <basicHttpBinding>
                <binding name="BasicHttpBinding_IService1">
                  <security mode="TransportCredentialOnly">
                    <transport clientCredentialType="None" />
                  </security>
                </binding>
              </basicHttpBinding>
            </bindings>
            <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
          </system.serviceModel>
          <system.webServer>
            <modules runAllManagedModulesForAllRequests="true"/>
          </system.webServer>
        </configuration>

Также у меня есть валидатор имени пользователя cutom, но он никогда не называется

    public class WpfCustomValidator :
      System.IdentityModel.Selectors.UserNamePasswordValidator
{
    public override void Validate(string userName, string password)
    {
        if (userName == null || password == null)
        {
            throw new ArgumentNullException();
        }
        var rf = WindsorAccessor.InitializeRepositoryFactory(userName);

        if (!ValidateLogOn(rf, userName, password))
        {
            throw new FaultException("Incorrect Username or Password");
        }
    }
}

Я хочу, чтобы в ответе было показано, как настроить клиент и службу, чтобы она могла видеть ClientCredentials.UserName.UserName в службе через HttpContext.Current.User.Identity.Name или через текущий идентификатор потока (или любым другим способом).

1 Ответ

1 голос
/ 10 декабря 2010

Доминик Байер показывает вам, как это сделать в своем блоге.

Ваш пользовательский код валидатора не вызывается, поскольку служба настроена для clientCredentialType = "None" - т.е. нетаутентификации.

...