0
Hello folks please I need your help.
I’m trying to send make the connection to the esocial api but I got the 403 return Forbidden, I’m with updated certificate and using jks. Below is the section where I load the certificate to make the request with webServiceTemplate
package br.jus.tjba.esocial.config;
import java.io.InputStream;
import java.net.Socket;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509KeyManager;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.ws.client.core.WebServiceTemplate;
import org.springframework.ws.transport.http.HttpComponentsMessageSender;
import org.springframework.ws.transport.http.HttpComponentsMessageSender.RemoveSoapHeadersInterceptor;
import br.jus.tjba.esocial.util.WsUtils;
/**
*
* @author Rafael Vasco, Vinicius Cidreira
*/
@Configuration
public class WsConfig {
@Value("${serpro.ssl.key-store}")
private Resource resourceKeyStore;
@Value("serpro.ssl.privatekey-store")
private Resource privateKey;
@Value("${serpro.ssl.key-store-password}")
private String resourceKeyStorePassword;
@Value("${serpro.ssl.private-key}")
private String privateKeyStorePassword;
@Value("${serpro.ssl.alias}")
private String alias;
@Value("${serpro.protocol}")
private String protocol;
@Bean
public WebServiceTemplate webServiceTemplate() throws Exception {
WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
webServiceTemplate.setMessageSender(httpComponentsMessageSender());
return webServiceTemplate;
}
public HttpComponentsMessageSender httpComponentsMessageSender() throws Exception {
HttpComponentsMessageSender httpComponentsMessageSender = new HttpComponentsMessageSender();
httpComponentsMessageSender.setHttpClient(httpClient());
return httpComponentsMessageSender;
}
public HttpClient httpClient() throws Exception {
return HttpClientBuilder.create().setSSLSocketFactory(sslConnectionSocketFactory())
.addInterceptorFirst(new RemoveSoapHeadersInterceptor())
.build();
}
public SSLConnectionSocketFactory sslConnectionSocketFactory() throws Exception {
// NoopHostnameVerifier essentially turns hostname verification off as otherwise
// following error
// is thrown: java.security.cert.CertificateException: No name matching
// localhost found
return new SSLConnectionSocketFactory(sslContext(), NoopHostnameVerifier.INSTANCE);
}
public SSLContext sslContext() throws Exception {
SSLContext sslContext = SSLContext.getInstance(protocol);
KeyStore keyStore = WsUtils.loadKeyStore(resourceKeyStore.getInputStream(), resourceKeyStorePassword.toCharArray());
PrivateKey privateKey = null;
try {
privateKey = (PrivateKey) keyStore.getKey(
alias,
privateKeyStorePassword.toCharArray()
);
} catch (Exception e) {
e.getMessage();
e.printStackTrace();
}
InputStream fileCacerts = WsUtils.getCacert();
X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);
final KeyManager[] keyManagers = createKeyManagers(keyStore, alias, certificate, privateKey);
final TrustManager[] trustManagers = createTrustManagers(fileCacerts);
sslContext.init(keyManagers, trustManagers, null);
fileCacerts.close();
return sslContext;
}
private KeyManager[] createKeyManagers(KeyStore keyStore, String alias, X509Certificate certificate, PrivateKey privateKey) {
return new KeyManager[]{new NFKeyManager(keyStore, alias, certificate, privateKey)};
}
private TrustManager[] createTrustManagers(InputStream fileCacerts) throws Exception {
final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(fileCacerts, resourceKeyStorePassword.toCharArray());
trustManagerFactory.init(trustStore);
return trustManagerFactory.getTrustManagers();
}
class NFKeyManager implements X509KeyManager {
private final X509Certificate certificate;
private final PrivateKey privateKey;
private KeyStore keyStore;
private String alias;
NFKeyManager(KeyStore keyStore, String alias, final X509Certificate certificate, final PrivateKey privateKey) {
this.certificate = certificate;
this.privateKey = privateKey;
this.keyStore = keyStore;
this.alias = alias;
}
@Override
public String chooseClientAlias(final String[] arg0, final Principal[] arg1, final Socket arg2) {
return this.certificate.getIssuerDN().getName();
}
@Override
public String chooseServerAlias(final String arg0, final Principal[] arg1, final Socket arg2) {
return null;
}
@Override
public X509Certificate[] getCertificateChain(final String arg0) {
try {
Certificate[] certificates = keyStore.getCertificateChain(alias);
X509Certificate[] x509Certificates = new X509Certificate[certificates.length];
System.arraycopy(certificates, 0, x509Certificates, 0, certificates.length);
return x509Certificates;
} catch (KeyStoreException e) {
return new X509Certificate[]{this.certificate};
}
}
@Override
public String[] getClientAliases(final String arg0, final Principal[] arg1) {
return new String[]{this.certificate.getIssuerDN().getName()};
}
@Override
public PrivateKey getPrivateKey(final String arg0) {
return this.privateKey;
}
@Override
public String[] getServerAliases(final String arg0, final Principal[] arg1) {
return null;
}
}
}
here the xml generated for sending
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.esocial.gov.br/schema/lote/eventos/envio/v1_1_1">
<soap:Body>
<v1:EnviarLoteEventos>
<v1:loteEventos>
<eSocial xmlns="http://www.esocial.gov.br/schema/lote/eventos/envio/v1_1_1">
<envioLoteEventos grupo="1">
<ideEmpregador>
<tpInsc>1</tpInsc>
<nrInsc>13100760</nrInsc>
</ideEmpregador>
<ideTransmissor>
<tpInsc>1</tpInsc>
<nrInsc>131007221111444</nrInsc>
</ideTransmissor>
<eventos>
<evento Id="ID1131007220000002019081317143000001">
<eSocial xmlns="http://www.esocial.gov.br/schema/evt/evtInfoEmpregador/v02_04_02">
<idEvento>ID11310072200888888888081317143555555</idEvento>
<evtInfoEmpregador Id="ID1131007220000002019081317143000001">
<ideEmpregador>
<tpInsc>1</tpInsc>
<nrInsc>13100722</nrInsc>
</ideEmpregador>
<infoEmpregador>
<inclusao>
<idePeriodo>
<iniValid>2019-07</iniValid>
</idePeriodo>
<infoCadastro>
<nmRazao>TJBAA</nmRazao>
<classTrib>85</classTrib>
<natJurid>1082</natJurid>
<indCoop>0</indCoop>
<indConstr>0</indConstr>
<indDesFolha>0</indDesFolha>
<indOptRegEletron>1</indOptRegEletron>
<indEntEd>N</indEntEd>
<indEtt>N</indEtt>
<contato>
<nmCtt>TESTE PIMENTA</nmCtt>
<cpfCtt>78177766520</cpfCtt>
<foneFixo>7133721896</foneFixo>
<foneCel>71988925970</foneCel>
</contato>
<infoOP>
<indUGRPPS>N</indUGRPPS>
<esferaOP>2</esferaOP>
<poderOP>2</poderOP>
<vrTetoRem>33763</vrTetoRem>
<ideEFR>N</ideEFR>
<cnpjEFR>13937032000160</cnpjEFR>
</infoOP>
<infoOrgInternacional>
<indAcordoIsenMulta>0</indAcordoIsenMulta>
</infoOrgInternacional>
<softwareHouse>
<cnpjSoftHouse>13100722</cnpjSoftHouse>
<nmRazao>TESTE TESTE</nmRazao>
<nmCont>LEANDRO SADY RODRIGUES</nmCont>
<telefone>71999999999</telefone>
<email>[email protected]</email>
</softwareHouse>
<infoComplementares>
<situacaoPJ>
<indSitPJ>0</indSitPJ>
</situacaoPJ>
</infoComplementares>
</infoCadastro>
</inclusao>
</infoEmpregador>
</evtInfoEmpregador>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
<SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
<Reference URI="">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
<Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
<DigestValue>[...]</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>[...]</SignatureValue>
<KeyInfo>
<X509Data>
<X509Certificate>[...]</X509Certificate>
</X509Data>
</KeyInfo>
</Signature>
</eSocial>
</evento>
</eventos>
</envioLoteEventos>
</eSocial>
</v1:loteEventos>
</v1:EnviarLoteEventos>
</soap:Body>
</soap:Envelope>
Here’s the excerpt where I send the xml above
RetornoEnvio response = (RetornoEnvio) webServiceTemplate.sendAndReceive(settings.getUrlEnviarlotes(),
soapActionCallback, new WebServiceMessageExtractor<Object>() {
public Object extractData(WebServiceMessage response) throws IOException {
Assert.isInstanceOf(SoapMessage.class, response);
SoapMessage soapMessage = (SoapMessage) response;
try {
final StringWriter sw = new StringWriter();
TransformerFactory.newInstance().newTransformer()
.transform(new DOMSource(soapMessage.getDocument()), new StreamResult(sw));
JAXBContext context = JAXBContext.newInstance(RetornoEnvio.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance()
.createXMLStreamReader(new StringReader(
XMLUtils.extractValueByTag(sw.toString(), "EnviarLoteEventosResult")));
XMLReaderWithoutNamespace readerWithoutNamespace = new XMLReaderWithoutNamespace(
xmlStreamReader);
RetornoEnvio retorno = (RetornoEnvio) unmarshaller.unmarshal(readerWithoutNamespace);
retorno.setXmlEnvio(xmlEnvio);
return retorno;
} catch (Exception e) {
throw new IOException("Error in unmarshaller xml return.", e);
}
}
});
I don’t know where I’m going wrong, in case you need more details just talk I’ve tried almost everything and always return the same error I can access the url through the browser and the event I’m trying to send is the S1000.
What is the WS url?
– thiaguerd
https://webservices.producaorestrita.esocial.gov.br/servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc
– Mateus Vinicius