Inquiridor
Serviço com autenticação e uso de certificado.

Pergunta
-
Boa noite pessoal!
Estou desenvolvendo um serviço com autenticação e uso de certificados para criptografia.
Vejam a classe que faz a validação de usuário e senha (código apenas de teste)
namespace MeuServico.Servico.Seguranca public class Autenticacao : UserNamePasswordValidator { public override void Validate(string userName, string password) { if (userName == null || password == null) { throw new ArgumentNullException(); } if (!(userName == "teste" && password == "senha")) { throw new FaultException("Unknown username or invalid password"); } } }
O código do serviço segue abaixo
namespace MeuServico.Servico { public class AutenticacaoServico : IAutenticacaoServico { private ServiceHost HostServer; public AutenticacaoServico() { HostServer = new ServiceHost(typeof(IAutenticacaoServico), new Uri[] { }); HostServer.Open(); } public void DoWork() { throw new NotImplementedException(); } } }
Web.config do serviço
<?xml version="1.0"?> <configuration> <system.serviceModel> <bindings> <wsHttpBinding> <binding name="wsHttpBindingWithMessageSecurity"> <security mode="Message"> <message clientCredentialType="UserName"/> </security> </binding> </wsHttpBinding> </bindings> <services> <service name="MeuServico.Servico.AutenticacaoServico" behaviorConfiguration="ServiceBehavior"> <endpoint address="http://localhost:50385/" binding="wsHttpBinding" bindingConfiguration="wsHttpBindingWithMessageSecurity" contract="MeuServico.Servico.IAutenticacaoServico"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> <host> <baseAddresses> <add baseAddress="http://localhost:50385/"/> </baseAddresses> </host> </service> </services> <behaviors> <serviceBehaviors> <behavior name="ServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="False"/> <serviceCredentials> <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="MeuServico.Servico.Seguranca.Autenticacao, MeuServico.Servico"/> <serviceCertificate findValue="chave" x509FindType="FindBySubjectName" storeLocation="LocalMachine" storeName="My"/> <clientCertificate> <authentication certificateValidationMode="None"></authentication> </clientCertificate> </serviceCredentials> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> <system.web> <compilation debug="true"/> </system.web> </configuration>
Criei e instalei o certificado usando SelfCert.
Na aplicação cliente adicionei referencia ao meu serviço e no controller da pagina de login coloquei a chamada ao método do serviço
AutenticacaoServicoClient autenticacao = new AutenticacaoServicoClient(); autenticacao.ClientCredentials.UserName.UserName = "teste"; autenticacao.ClientCredentials.UserName.Password = "senha"; autenticacao.DoWork();
Web.config do cliente
<?xml version="1.0" encoding="utf-8"?> <!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <appSettings> <add key="webpages:Version" value="2.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="PreserveLoginUrl" value="true" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings> <system.web> <httpRuntime targetFramework="4.5" /> <compilation debug="true" targetFramework="4.5" /> <pages> <namespaces> <add namespace="System.Web.Helpers" /> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> <add namespace="System.Web.WebPages" /> </namespaces> </pages> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false" /> </system.webServer> <system.serviceModel> <bindings> <wsHttpBinding> <binding name="WSHttpBinding_IAutenticacaoServico"> <security> <message clientCredentialType="UserName" /> </security> </binding> </wsHttpBinding> </bindings> <client> <endpoint address="http://localhost:50385/" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IAutenticacaoServico" contract="AutenticacaoServico.IAutenticacaoServico" name="WSHttpBinding_IAutenticacaoServico"> <identity> <dns value="localhost" /> </identity> </endpoint> </client> </system.serviceModel> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>
Mas rodando a aplicação e ao chamar o metodo DoWork() aparece um erro de execução e mal chega no breakpoint que coloquei no serviço.
Erro de Servidor no Aplicativo '/'.
O servidor remoto retornou um erro: (405) Método Não Permitido.
Descrição: Ocorreu uma exceção sem tratamento durante a execução da atual solicitação da Web. Examine o rastreamento de pilha para obter mais informações sobre o erro e onde foi originado no código.
Detalhes da Exceção: System.Net.WebException: O servidor remoto retornou um erro: (405) Método Não Permitido.
Erro de Origem:
Linha 51: Linha 52: public void DoWork() { Linha 53: base.Channel.DoWork(); Linha 54: } Linha 55:
Arquivo de Origem: e:\Projetos\Donate\Fontes\Donate\Donate.Administrador\Donate.Administrador\Service References\AutenticacaoServico\Reference.cs Linha: 53
Rastreamento de Pilha:
[WebException: O servidor remoto retornou um erro: (405) Método Não Permitido.] System.Net.HttpWebRequest.GetResponse() +6594148 System.ServiceModel.Channels.HttpChannelRequest.WaitForReply(TimeSpan timeout) +55 [ProtocolException: O servidor remoto retornou uma resposta inesperada: (405) Method Not Allowed.] System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +10992471 System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +336 Donate.Administrador.AutenticacaoServico.IAutenticacaoServico.DoWork() +0 Donate.Administrador.AutenticacaoServico.AutenticacaoServicoClient.DoWork() in e:\Projetos\Donate\Fontes\Donate\Donate.Administrador\Donate.Administrador\Service References\AutenticacaoServico\Reference.cs:53 Donate.Controllers.AccountController.Login(LoginModel model, String returnUrl) in e:\Projetos\Donate\Fontes\Donate\Donate.Administrador\Donate.Administrador\Controllers\AccountController.cs:35 lambda_method(Closure , ControllerBase , Object[] ) +245 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +59 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +434 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +60 System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeSynchronousActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +50 System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +75 System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +44 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +139 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49 System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +126 System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +323 System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +44 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +139 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50 System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +68 System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +184 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +136 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40 System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +40 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39 System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +45 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9690164 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Informações sobre a Versão: Microsoft .NET Framework Versão:4.0.30319; Versão do ASP.NET:4.0.30319.34009Alguém pode me dar um luz? :)
- Editado Hélio Dutra de Oliveira quarta-feira, 9 de abril de 2014 02:17