Inquiridor
NFE A solicitação HTTP está proibida com o esquema de autenticação de cliente 'Anonymous'.

Pergunta
-
Ola galera, alguem pode me ajudar??.Estou desenvolvendo uma integração com o nfe, consigo validar o xml, consigo assinar o arquivo xml, mas esta dando o erro:A solicitação HTTP está proibida com o esquema de autenticação de cliente 'Anonymous'.o meu codigo é o seguinte:
public string ConsultaCadastroP(string dados) { X509Certificate2 certificado = new X509Certificate2(); EscolheCertificado escolhe = new EscolheCertificado(); certificado = escolhe.certificado(); CRIARXML criarCab = new CRIARXML(); ConsultaCadastroH.CadConsultaCadastroSoapClient teste = new NFE_MATERCOP.ConsultaCadastroH.CadConsultaCadastroSoapClient(); System.ServiceModel.EndpointAddress endereco = new System.ServiceModel.EndpointAddress("https://homologacao.nfe.fazenda.sp.gov.br/nfeWEB/services/cadconsultacadastro.asmx?WSDL"); teste.Endpoint.Address = endereco; teste.ClientCredentials.ClientCertificate.Certificate = certificado; teste.Open(); string RETOrno; try { RETOrno = teste.consultaCadastro(criarCab.gerarCabecalho("1.07"), dados); } catch (Exception err) { RETOrno = err.Message; teste.Abort(); } teste.Close(); return RETOrno; }
Todas as Respostas
-
Verifique se você não está tentando passar o endereço como HTTP,no caso de nf-e o protocolo é https, você tem que passar suas credenciais que são na verdade o caminho do seu certificado e a senha do mesmo.
Tipo:
X509Certificate2 certificado = new X509Certificate2(caminhoDoseuCertificado, senhaDoseuCertificado);
Elielson de Andrade elielson( a )gd.com.br www.despcompany.com www.emyface.com -
Verifique se você não está tentando passar o endereço como HTTP,no caso de nf-e o protocolo é https, você tem que passar suas credenciais que são na verdade o caminho do seu certificado e a senha do mesmo.
Tipo:
X509Certificate2 certificado = new X509Certificate2(caminhoDoseuCertificado, senhaDoseuCertificado);
Elielson de Andrade elielson( a )gd.com.br www.despcompany.com www.emyface.comBom dia Elielson de Andrade,
Estou passando todos os dados corretamente e mesmo assim a mensagem continua, olhe meu código:
public String NfeStatusServico(String cUF, String versaoDados, XmlDocument xmlAssinado, X509Certificate2 certificado)
{
try
{
HomoNfeStatusServico2.nfeCabecMsg _nfeCabecMsg = new HomoNfeStatusServico2.nfeCabecMsg();
_nfeCabecMsg.cUF = cUF;
_nfeCabecMsg.versaoDados = versaoDados;
HomoNfeStatusServico2.NfeStatusServico2Soap12Client teste = new HomoNfeStatusServico2.NfeStatusServico2Soap12Client();
System.ServiceModel.EndpointAddress endereco = new System.ServiceModel.EndpointAddress("https://homologacao.nfe.fazenda.sp.gov.br/nfeweb/services/NfeStatusServico2.asmx ");
teste.Endpoint.Address = endereco;
teste.ClientCredentials.ServiceCertificate.DefaultCertificate = certificado;
teste.ClientCredentials.ClientCertificate.Certificate = certificado;
return teste.nfeStatusServicoNF2 (ref _nfeCabecMsg, xmlAssinado).OuterXml;
}
catch (Exception a)
{
return a.Message;
}
}Você tem alguma ideia de por que ainda recebo este estatus?
IGOR GOLDIM
-
Solução.
http://balaiotecnologico.blogspot.com.br/2011/03/problemas-comuns-ao-consumir-web.html
Há particularmente dois parâmetros neste arquivo cujos valores padrões diferem do exigido pelo servidor da Receita: authenticationScheme e requireClientCertificate. O primeiro indica como o usuário será validado, sendo que o valor padrão é"Anonymous" para indicar que nenhuma validação é esperada. Como eu disse antes, o servidor da Receita só libera o acesso se um certificado foi informado. Portanto, o valor desse parâmetro deve ser alterado para "Digest". O segundo parâmetro deve ter valor "true", confirmando que o servidor exige que sua aplicação envie os dados do certificado para garantir a autenticação. O quadro abaixo traz o trecho de umapp.config como exemplo, mostrando como fica a configuração para o serviço de consulta de uma nota fiscal:
<binding name="NfeConsulta2Soap12">
...
<httpsTransport authenticationScheme="Digest"requireClientCertificate="true" ... />
</binding>IGOR GOLDIM
- Sugerido como Resposta Josivan Laskoski terça-feira, 9 de julho de 2013 14:31
-
Bom dia pessoal,
Estou com o mesmo problema, mas como estou fazendo uma DLL, preciso transcrever o que está no web.config para dentro da minha classe.
segue meu codigo:
private List<CadConsultaWeb.CadConsultaCadastro2Soap12> fields = new List<CadConsultaWeb.CadConsultaCadastro2Soap12>(); private BasicHttpBinding basicHttpBinding = new BasicHttpBinding() { MaxBufferSize = int.MaxValue, MaxReceivedMessageSize = int.MaxValue }; private EndpointAddress endpointAddress = new EndpointAddress("https://homologacao.nfe.fazenda.sp.gov.br/nfeweb/services/CadConsultaCadastro2.asmx"); private CadConsultaWeb.CadConsultaCadastro2Soap12Client wsTransacional; private CadConsultaWeb.nfeCabecMsg cab = new CadConsultaWeb.nfeCabecMsg(); //private HttpProxyCredentialType credencial = new HttpProxyCredentialType.Digest; private string retorno = ""; public void configuraWebConfig(string _caminhoCertificadoDigital, string _senhaCertificadoDigital) { SecurityBindingElement securityElement = SecurityBindingElement.CreateSslNegotiationBindingElement(true); HttpsTransportBindingElement httpstransport = new HttpsTransportBindingElement(); httpstransport.AllowCookies = false; httpstransport.BypassProxyOnLocal = false; httpstransport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; httpstransport.MaxBufferSize = 65536; httpstransport.MaxBufferPoolSize = 524288; httpstransport.MaxReceivedMessageSize = 65536; httpstransport.TransferMode = TransferMode.Buffered; httpstransport.UseDefaultWebProxy = true; httpstransport.AuthenticationScheme = System.Net.AuthenticationSchemes.Digest; httpstransport.ManualAddressing = false; httpstransport.AllowCookies = false; httpstransport.BypassProxyOnLocal = false; //httpsTransport.DecompressionEnabled = true; httpstransport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; httpstransport.KeepAliveEnabled = true; httpstransport.ProxyAuthenticationScheme = System.Net.AuthenticationSchemes.Digest; httpstransport.Realm = ""; httpstransport.TransferMode = TransferMode.Buffered; httpstransport.UnsafeConnectionNtlmAuthentication = true; httpstransport.UseDefaultWebProxy = true; CustomBinding customBinding = new CustomBinding(securityElement,httpstransport); TextMessageEncodingBindingElement oTextMessageEncod = new TextMessageEncodingBindingElement(); oTextMessageEncod.MaxReadPoolSize = 64; oTextMessageEncod.MaxWritePoolSize = 16; oTextMessageEncod.MessageVersion = MessageVersion.Soap12; oTextMessageEncod.WriteEncoding = Encoding.UTF8; customBinding.Elements.Add(oTextMessageEncod); customBinding.Elements.Add(httpstransport); basicHttpBinding.Name = "CadConsultaCadastro2Soap12"; basicHttpBinding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.Transport; basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate; wsTransacional = new CadConsultaWeb.CadConsultaCadastro2Soap12Client(customBinding, endpointAddress); wsTransacional.Endpoint.Binding = basicHttpBinding; wsTransacional.Endpoint.Address = endpointAddress; wsTransacional.Endpoint.Name = "CadConsultaCadastro2Soap12"; wsTransacional.Endpoint.Contract.Name = "CadConsultaWeb.CadConsultaCadastro2Soap12"; X509Certificate2 certificado = new X509Certificate2(_caminhoCertificadoDigital, _senhaCertificadoDigital); wsTransacional.ClientCredentials.ClientCertificate.Certificate = certificado; } [WebMethod] public string ConsultaCadastro(string _uf, string _versaoDados, string _ufConsulta, string _ieContribuinte, string _cnpj, string _cpf, string _caminhoCertificadoDigital, string _senhaCertificadoDigital) { configuraWebConfig(_caminhoCertificadoDigital, _senhaCertificadoDigital); cab.cUF = "42";//_uf; cab.versaoDados = _versaoDados; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", String.Empty)); XmlNode nodeCab = xmlDoc.CreateNode(System.Xml.XmlNodeType.Element, "ConsCad", ""); XmlAttribute atributoVersao = xmlDoc.CreateAttribute("versao"); atributoVersao.Value = "1.03"; nodeCab.Attributes.Append(atributoVersao); XmlAttribute atributoHttp = xmlDoc.CreateAttribute("xmlns:ds"); atributoHttp.Value = "http://www.w3.org/20000/09/xmldsig#"; nodeCab.Attributes.Append(atributoHttp); XmlAttribute atributoxsd = xmlDoc.CreateAttribute("xmlns:xsd"); atributoxsd.Value = "http://www.w3.org/2001/XMLSchema"; nodeCab.Attributes.Append(atributoxsd); XmlAttribute atributosoap = xmlDoc.CreateAttribute("xmlns:soap12"); atributosoap.Value = "http://www.w3.org/2003/05/soap-envelope"; nodeCab.Attributes.Append(atributosoap); /*-- XmlAttribute atributonamespace = xmlDoc.CreateAttribute("xmlns"); atributonamespace.Value = "http://www.portalfiscal.inf.br/nfe"; nodeCab.Attributes.Append(atributonamespace);*/ xmlDoc.AppendChild(nodeCab); XmlNode nodeInf = xmlDoc.CreateNode(System.Xml.XmlNodeType.Element, "infCons", ""); nodeCab.AppendChild(nodeInf); XmlNode userNode = xmlDoc.CreateElement("xServ"); userNode.InnerText = "CONS-CAD"; nodeInf.AppendChild(userNode); userNode = xmlDoc.CreateElement("UF"); userNode.InnerText = _ufConsulta; nodeInf.AppendChild(userNode); /* userNode = xmlDoc.CreateElement("IE"); if (!_ieContribuinte.Equals("")) { userNode.InnerText = _ieContribuinte; } nodeInf.AppendChild(userNode); userNode = xmlDoc.CreateElement("CNPJ"); if (!_cnpj.Equals("")) { userNode.InnerText = _cnpj; } nodeInf.AppendChild(userNode); */ userNode = xmlDoc.CreateElement("CPF"); if (!_cpf.Equals("")) { userNode.InnerText = _cpf; } nodeInf.AppendChild(userNode); xmlDoc.Save("c:\\test-doc.xml"); XmlNode status = wsTransacional.consultaCadastro2(ref cab, xmlDoc); return retorno; }
O erro é o mesmo:
System.ServiceModel.Security.MessageSecurityException: A solicitação HTTP ESTA Proibida com o Esquema de Autenticação de Cliente 'Anonymous'. ---> System.Net.WebException: O Servidor Remoto retornou hum Erro: (403) Proibido. los System.Net.HttpWebRequest.GetResponse () los timeout) --- Fim do Rastreamento da Pilha de Exceções Internas ---
Se alguem puder me ajudar, obrigado!!
-
Josivan
Você conseguiu resolver o seu problema acima, hoje o meu app.config está assim :
<?xml version="1.0"?>
<configuration>
<system.diagnostics>
<sources>
<!-- This section defines the logging configuration for My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
<!-- Uncomment the below section to write to the Application Event Log -->
<!--<add name="EventLog"/>-->
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information"/>
</switches>
<sharedListeners>
<add name="FileLog" type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" initializeData="FileLogWriter"/>
<!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
<!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
</sharedListeners>
</system.diagnostics>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>No caso do trecho abaixo, em qual local devo colocar dentro do meu ?
<binding name="NfeConsulta2Soap12">
...
<httpsTransport authenticationScheme="Digest" requireClientCertificate="true" ... />
</binding> -
Pessoal
Veja como está o meu abaixo, mais ainda não consegui ?
<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <bindings> <customBinding> <binding name="nfestatusservico2Soap12"> <textMessageEncoding messageVersion="Soap12" /> <httpsTransport authenticationScheme="Digest" requireClientCertificate="true" /> </binding> </customBinding> </bindings> <client> <endpoint address="https://nfe.fazenda.sp.gov.br/nfeweb/services/nfestatusservico2.asmx" binding="customBinding" bindingConfiguration="nfestatusservico2Soap12" contract="nfeweb.services.nfestatusservico2Soap12" name="nfestatusservico2Soap12" /> </client> </system.serviceModel> </configuration>