none
Método Validade não é executado - UserNamePasswordValidator RRS feed

  • Pergunta

  • Boa noite,

    Estou iniciando em WCF e estou tentando usar a autenticação porém o método Validate não é executado, o serviço retorna os dados sem autenticação.

     

    Segue classe a qual implementa a interface:

    public override void Validate(string userName, string password)

            {

                //ValidateUser ae = new ValidateUser();

                //ae.ValidateUsers(userName, password);

                if (userName != "leandro" || password != "1234")

                {

                    throw new SecurityTokenValidationException("The provided credentials are invalid.");

                }

     

     

            }

    Meu config esta dessa forma:

    <system.serviceModel>

        <bindings>

          <basicHttpBinding>

            <binding name="BasicHttpCredentialsValidation">

              <security mode="TransportCredentialOnly">

                <message clientCredentialType="UserName"/>

              </security>

            </binding>

          </basicHttpBinding>

          <webHttpBinding>

            <binding name="RESTwebHttpBinding">

              <security mode ="None"></security>

            </binding>

          </webHttpBinding>

        </bindings>

        <services>

          <service behaviorConfiguration="Behavior1" name="WcfServiceProject.Service1">

            <endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpCredentialsValidation"

              contract="WcfServiceProject.IService1" />

            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />

            <host>

              <baseAddresses>

                <add baseAddress="http://localhost/" />

              </baseAddresses>

            </host>

          </service>

        </services>

        <behaviors>

          <serviceBehaviors>

            <behavior name="Behavior1">

              <serviceCredentials>

                <userNameAuthentication userNamePasswordValidationMode="Custom"

                 customUserNamePasswordValidatorType="WcfServiceProject.Authentication, WcfServiceProject" />

                <serviceCertificate findValue="Leandro" storeLocation="LocalMachine" storeName="TrustedPeople" x509FindType="FindBySubjectName"/>

                <clientCertificate>

                  <authentication trustedStoreLocation="LocalMachine" certificateValidationMode="None" />

                </clientCertificate>

              </serviceCredentials>

              <serviceMetadata httpGetEnabled="True"/>

              <serviceDebug includeExceptionDetailInFaults="true"/>

            </behavior>

          </serviceBehaviors>

          <endpointBehaviors>

            <behavior name="RestEndpointBehavior">

              <webHttp/>

            </behavior>

          </endpointBehaviors>

        </behaviors>

      </system.serviceModel>

     

    O que esta faltando, pois de forma alguma a autenticação ocorre, se eu colocar qualquer usuário e senha o serviço retorna os dados normalmente.

    Obrigado.


    Leandro
    terça-feira, 8 de novembro de 2011 22:29

Todas as Respostas

  • Fala leandro.

    Você consegue debugar o serviço?

    Quando você faz uma chamada com o cliente, ele nem chega a bater no serviço correto?

    Pode ser 2 problemas que vejo de prima:

    1)

    seu tipo da classe validator tem que ser customUserNamePasswordValidatorType="<<NamespaceDoPRojeto.Nome daClass>>, <<nomeDoAssembly>>" />

    customUserNamePasswordValidatorType="WcfServiceProject.Authentication, WcfServiceProject" />

    lembre-se que não necessariamente o nome do namespace é o nome do assembly apesar do VS criar dessa forma quando se cria uma novo projeto, para ter certeza va em properties do seu projeto no VS e verifique o assemblyName.

    2)

    Seu certificado não ta funcionando.

    Tente tirar a segurança do binding só para testar se seu serviço está funcionando corretamente, você consegue fazer isso eliminando a tag bindingConfiguration="BasicHttpCredentialsValidation".

     

    Tente isolar o problema

     

    abraços

     

     


    Alberto Cardoso
    segunda-feira, 14 de novembro de 2011 09:59
  • Boas Leandro,

    Eu acredito que a configuração no web.config não esteja encontrando o tipo do autenticador.
    http://www.israelaece.com
    quarta-feira, 16 de novembro de 2011 00:46
    Moderador
  • Alberto,Israel obrigado pelo retorno,

    Eu consigo debugar o serviço normalmente com os métodos a quais criei. Retirei o bindingConfiguration ficando dessa forma:

    <services>

          <service behaviorConfiguration="Behavior1" name="WcfServiceProject.Service1">

            <endpoint address="" binding="basicHttpBinding" contract="WcfServiceProject.IService1" />

            <host>

              <baseAddresses>

                <add baseAddress="http://localhost/" />

              </baseAddresses>

            </host>

          </service>

        </services>

    e mesmo assim o método Validate não é executado.

    Verifiquei a procedência referente ao trecho:

    <userNameAuthentication userNamePasswordValidationMode="Custom"

                 customUserNamePasswordValidatorType="WcfServiceProject.Authentication, WcfServiceProject"/>

    consultei o nome do assembly nas propriedades do projeto e está correto sendo: WcfServiceProject

    abaixo segue a classe a qual representa WcfServiceProject.Authentication

    namespace WcfServiceProject
    {
        public class Authentication : UserNamePasswordValidator
        {
            public override void Validate(string userName, string password)
            {
                //ValidateUser ae = new ValidateUser();
                //ae.ValidateUsers(userName, password);
                //if (userName != "leandro" || password != "1234")
                //{
                    throw new SecurityTokenException("The provided credentials are invalid.");
                //}
            }
        }
    }

    mesmo teoricamente estando tudo correto o método validate não é executado e não entra no breakpoint.

    Israel você mencionou que talvez não esteja sendo encontrado o tipo do autenticador, não geraria algum erro referente a não encontrar,algo que eu possa fazer para achar a solução do problema??

    Obrigado.


    Leandro
    segunda-feira, 21 de novembro de 2011 02:04
  • Leandro bom dia,

    Primeiramente você deve ver se seu certificado está realmente instalado. Eu utilizei o programa PluralSight SelfCert, ele cria certificados locais na maquina.

    No meu caso eu utilizei o binding wsHttpBinding, com autenticação na Mensagem, fica mais ou menos assim:

    <security mode="Message"

    >

    <message clientCredentialType="UserName" negotiateServiceCredential="False"

     

     

     

    algorithmSuite="Default"

    />

    </

     

    security>

    Não esqueça de atualizar o proxy depois.

    Qualquer coisa, poste o erro que está dando para tentarmos ajudar melhor.

    Abraçossss!!

    quinta-feira, 24 de novembro de 2011 11:18
  • Israel, boa noite..

     

    Estou com o mesmo problema do Leandro...

    Criei um serviço WCF, porém mesmo com todas as conexões de segurança, consigo instanciar e usar os métodos sem a utilização de senha.

     

    Seguem os códigos:

    CLSSEGURANCA.CS (Classe que fiz o override no método Validate)

     

        public class ClsSeguranca : UserNamePasswordValidator
        {
            public override void Validate(string userName, string password)
            {
                if (userName == null || password == null)
                {
                    throw new ArgumentNullException();
                }
    
                if (!(userName == "administrator" && password == "P@ssw0rd"))
                {
                    throw new FaultException("Unknown username or invalid password");
                }
            }
        }
    

     


    WEB CONFIG

     

    <?xml version="1.0"?>
    <configuration>
    	<configSections>
    		<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
    			<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
    				<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
    				<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
    					<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
    					<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
    					<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
    					<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/></sectionGroup></sectionGroup></sectionGroup></configSections><appSettings/>
    	<connectionStrings/>
    	<system.web>
    		<compilation debug="true">
    			<assemblies>
    				<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
    				<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    				<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
    				<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies></compilation>
    		<!--
            The <authentication> section enables configuration 
            of the security authentication mode used by 
            ASP.NET to identify an incoming user. 
        -->
    		<authentication mode="Forms"/>
    		<!--
            The <customErrors> section enables configuration 
            of what to do if/when an unhandled error occurs 
            during the execution of a request. Specifically, 
            it enables developers to configure html error pages 
            to be displayed in place of a error stack trace.
    
            <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
             <error statusCode="403" redirect="NoAccess.htm" />
             <error statusCode="404" redirect="FileNotFound.htm" />
            </customErrors>
        -->
    		<pages>
    			<controls>
    				<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    				<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></controls></pages>
    		<httpHandlers>
    			<remove verb="*" path="*.asmx"/>
    			<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    			<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    			<add verb="GET,HEAD" path="ScriptResource.axd" validate="false" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></httpHandlers>
    		<httpModules>
    			<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></httpModules></system.web>
    	<!-- 
          The system.webServer section is required for running ASP.NET AJAX under Internet
          Information Services 7.0.  It is not necessary for previous version of IIS.
      -->
    	<system.serviceModel>
    		<services>
    			<service behaviorConfiguration="TESTE_WCF.Service1Behavior" name="TESTE_WCF.ServicoExemplo">
            <host>
              <baseAddresses>
                <add baseAddress="http://localhost:29472/"/>
              </baseAddresses>
            </host>
    				<endpoint address="mee" binding="wsHttpBinding" contract="TESTE_WCF.IService1"/>
    				<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
    			</service>
    		</services>
    
        <bindings>
          <wsHttpBinding>
            <binding name="srvBindingConfig">
              <security mode ="Message">
                <message clientCredentialType="UserName" negotiateServiceCredential="False" algorithmSuite="Default" />
              </security>
            </binding>
          </wsHttpBinding>
        </bindings>
    
        <behaviors>
    			<serviceBehaviors>
    				<behavior name="TESTE_WCF.Service1Behavior">
    					<!-- 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="TESTE_WCF.ClsSeguranca, TESTE_WCF" />
                <windowsAuthentication allowAnonymousLogons="false"/>
              </serviceCredentials>
    				</behavior>
    			</serviceBehaviors>
    		</behaviors>
    	</system.serviceModel>
    	<system.codedom>
    			<compilers>
    				<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
    					<providerOption name="CompilerVersion" value="v3.5"/>
    					<providerOption name="WarnAsError" value="false"/></compiler></compilers></system.codedom>
    	<system.webServer>
    			<validation validateIntegratedModeConfiguration="false"/>
    		<modules>
    			<remove name="ScriptModule"/>
    			<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></modules>
    		<handlers>
    			<remove name="WebServiceHandlerFactory-Integrated"/>
    			<remove name="ScriptHandlerFactory"/>
    			<remove name="ScriptHandlerFactoryAppServices"/>
    			<remove name="ScriptResource"/>
    			<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    			<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    			<add name="ScriptResource" verb="GET,HEAD" path="ScriptResource.axd" preCondition="integratedMode" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></handlers></system.webServer>
    	<runtime>
    		<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1" appliesTo="v2.0.50727">
    			<dependentAssembly>
    				<assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
    				<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/></dependentAssembly>
    			<dependentAssembly>
    				<assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
    				<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/></dependentAssembly></assemblyBinding></runtime></configuration>
    
    

     

    CLIENTE:

     

                using (SR_WCF.Service1Client sv = new SR_WCF.Service1Client())
                {
                    //sv.ClientCredentials.UserName.UserName = "lucas";
                    //sv.ClientCredentials.UserName.Password = "123";
                    MessageBox.Show(sv.GetData(10));
                }
    

     


    Nota: mesmo com as linhas de usuário e senha comentadas, consigo obter o resultado do método GetData.

     

    Alguém pode me ajudar por favor?

     

    Grato,

    Lucas


    Lucas Cuccurullo Leite - C# Developer

    quinta-feira, 24 de novembro de 2011 21:13