How the mTLS client certificate works, why it protects your integration, how to request it and how to use it in your application.
What is mTLS
Every API request already travels over HTTPS (TLS) and only comes from the IP addresses registered for your company. In plain TLS, only the server shows a certificate: your application checks that it is talking to the real API, while the API recognizes your application by its IP address and credentials.
mTLS (Mutual TLS) makes the check go both ways. During the connection, your application also presents a client certificate, and the API only accepts the connection if that certificate was issued by us for your company.
| Before | With mTLS | |
|---|---|---|
| Who proves its identity in the connection | Only the API | The API and your application |
| What the API checks | Allowed IP address, access token and HMAC | Allowed IP address, client certificate, access token and HMAC |
| What identifies your application | IP address and credentials | IP address, credentials and a certificate with a private key that only you hold |
mTLS is a new layer. It does not replace anything you already do: the IP allowlist, the Bearer token and the HMAC signature remain required on every request.
How it works
- Your application opens an HTTPS connection to the API.
- The API sends its server certificate, as it already does today.
- The API asks your application for its client certificate.
- Your application sends the certificate and a signature made with the private key stored in the
.p12file. The private key never leaves your server. - The API checks that the certificate was issued by our certificate authority, is within its validity period, was not revoked and that the signature matches.
- The encrypted session is open, with both sides authenticated.
- Your application sends the API request as usual, with the
Authorizationandhmacheaders. - The API responds.
All of this happens inside your HTTP client library. In your code, the only change is to load the certificate once and attach it to the HTTP client, as shown in the examples below.
Why mTLS protects everyone
- Only authorized clients reach the API. A leaked access token,
client_secretorhmac_keyis not enough: without the certificate issued for your company, the connection is refused. - Protection against impersonation and interception. Both sides authenticate each other, which blocks man-in-the-middle attacks and connections from fake servers or fake clients.
- Encrypted data end to end. Everything exchanged travels encrypted, keeping the confidentiality and integrity of your transactions.
- Traceability. Every connection is tied to an identified certificate, which makes auditing and incident response faster.
- Regulatory compliance. Mutual authentication follows the security practices expected in the financial and payments system, such as the Central Bank of Brazil guidelines, PCI-DSS and LGPD.
How to request the certificate
Send an e-mail to [email protected] with the subject "Solicitação de certificado mTLS para integração com a API", informing:
- the company CNPJ;
- the accounts that use the integration;
- the institution the certificate must be issued for.
What you receive
| Item | Description |
|---|---|
| Certificate file | A .p12 file (PKCS#12) with your client certificate and its private key. |
| Password | The password that opens the .p12 file. |
| Validity | 365 days. Request a new certificate before it expires (see Renewal). |
| Scope | One certificate per company, used for all of its accounts. It only works in the environment it was issued for. |
Treat the.p12file and its password like a password. Anyone who has both can open connections in the name of your company.
Step 1: Prepare the certificate
Some languages read the .p12 file directly (Java, C#, cURL). Others work better with two PEM files: the certificate (client.crt) and the private key (client.key). Convert once with OpenSSL:
# Certificate (public part)
openssl pkcs12 -legacy -in client.p12 -clcerts -nokeys -out client.crt
# Private key (keep this file protected)
openssl pkcs12 -legacy -in client.p12 -nocerts -nodes -out client.key
chmod 600 client.keyOpenSSL asks for the .p12 password in each command.
About-legacy: the.p12file uses an encryption format that OpenSSL 3 only opens with the-legacyflag. If you use OpenSSL 1.1, remove the flag.
Check the certificate and its expiration date:
openssl x509 -in client.crt -noout -subject -enddateStep 2: Test the connection
Before changing your application, test with cURL. If the token is returned, the certificate is working.
curl https://api.somossimpay.com.br/v2/finance/auth-token/ \
--cert client.crt \
--key client.key \
-H "Content-Type: application/json" \
-d '{"client_id":"your-client-id","client_secret":"your-client-secret"}'Using the .p12 file directly:
curl https://api.somossimpay.com.br/v2/finance/auth-token/ \
--cert-type P12 \
--cert "client.p12:your-p12-password" \
-H "Content-Type: application/json" \
-d '{"client_id":"your-client-id","client_secret":"your-client-secret"}'Replace https://api.somossimpay.com.br with the API address you already use.
Step 3: Use it in your application
Load the certificate once, when the application starts, and reuse the same HTTP client for every request. Keep sending the Authorization and hmac headers exactly as today.
Examples by language
Python (requests)
import os
import requests
session = requests.Session()
session.cert = (os.environ["MTLS_CERT_PATH"], os.environ["MTLS_KEY_PATH"]) # client.crt, client.key
response = session.post(
"https://api.somossimpay.com.br/v2/finance/auth-token/",
json={
"client_id": os.environ["CLIENT_ID"],
"client_secret": os.environ["CLIENT_SECRET"],
},
timeout=30,
)
response.raise_for_status()
access_token = response.json()["access_token"]Node.js (https / axios)
const fs = require('fs');
const https = require('https');
const axios = require('axios');
const httpsAgent = new https.Agent({
cert: fs.readFileSync(process.env.MTLS_CERT_PATH), // client.crt
key: fs.readFileSync(process.env.MTLS_KEY_PATH), // client.key
keepAlive: true,
});
const api = axios.create({
baseURL: 'https://api.somossimpay.com.br',
httpsAgent,
timeout: 30000,
});
async function getToken() {
const { data } = await api.post('/v2/finance/auth-token/', {
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
});
return data.access_token;
}
Use the PEM files (certandkey) in Node.js. Passing the.p12file in thepfxoption fails on Node.js 17 or later withUnsupported PKCS12 PFX data, because of the legacy encryption mentioned in Step 1.
Java (11+, java.net.http)
import java.io.FileInputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
public class MtlsClient {
public static void main(String[] args) throws Exception {
char[] password = System.getenv("MTLS_P12_PASSWORD").toCharArray();
KeyStore keyStore = KeyStore.getInstance("PKCS12");
try (FileInputStream in = new FileInputStream(System.getenv("MTLS_P12_PATH"))) {
keyStore.load(in, password);
}
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, password);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), null, null);
HttpClient client = HttpClient.newBuilder().sslContext(sslContext).build();
String body = "{\"client_id\":\"" + System.getenv("CLIENT_ID")
+ "\",\"client_secret\":\"" + System.getenv("CLIENT_SECRET") + "\"}";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.somossimpay.com.br/v2/finance/auth-token/"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
}
}C# (.NET 6+)
using System.Net.Http.Json;
using System.Security.Cryptography.X509Certificates;
var certificate = new X509Certificate2(
Environment.GetEnvironmentVariable("MTLS_P12_PATH"),
Environment.GetEnvironmentVariable("MTLS_P12_PASSWORD"));
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(certificate);
// Create once and reuse for the whole application
var client = new HttpClient(handler) { BaseAddress = new Uri("https://api.somossimpay.com.br") };
var response = await client.PostAsJsonAsync("/v2/finance/auth-token/", new
{
client_id = Environment.GetEnvironmentVariable("CLIENT_ID"),
client_secret = Environment.GetEnvironmentVariable("CLIENT_SECRET"),
});
response.EnsureSuccessStatusCode();PHP (cURL)
<?php
$ch = curl_init('https://api.somossimpay.com.br/v2/finance/auth-token/');
curl_setopt_array($ch, [
CURLOPT_SSLCERT => getenv('MTLS_CERT_PATH'), // client.crt
CURLOPT_SSLKEY => getenv('MTLS_KEY_PATH'), // client.key
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode([
'client_id' => getenv('CLIENT_ID'),
'client_secret' => getenv('CLIENT_SECRET'),
]),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
]);
$response = curl_exec($ch);
if ($response === false) {
throw new Exception('Connection error: ' . curl_error($ch));
}
curl_close($ch);Go
package main
import (
"bytes"
"crypto/tls"
"net/http"
"os"
"time"
)
func main() {
cert, err := tls.LoadX509KeyPair(os.Getenv("MTLS_CERT_PATH"), os.Getenv("MTLS_KEY_PATH"))
if err != nil {
panic(err)
}
client := &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{Certificates: []tls.Certificate{cert}},
},
}
body := []byte(`{"client_id":"your-client-id","client_secret":"your-client-secret"}`)
resp, err := client.Post("https://api.somossimpay.com.br/v2/finance/auth-token/", "application/json", bytes.NewReader(body))
if err != nil {
panic(err)
}
defer resp.Body.Close()
}Postman
- Open Settings → Certificates → Client certificates → Add certificate.
- In Host, type the API address without
https://(for exampleapi.example.com). - Select
client.crtin CRT file andclient.keyin KEY file. - Save. Postman sends the certificate on every request to that host, and your token and HMAC scripts keep working.
Renewal and revocation
- The certificate is valid for 365 days. Write down the expiration date (
openssl x509 -in client.crt -noout -enddate) and set an alert at least 30 days before it. - To renew, send a new request to [email protected] with the same information. Install the new certificate before the old one expires.
- If the
.p12file, its password or the private key may have been exposed, contact [email protected] immediately so we revoke the certificate and issue a new one.
Security best practices
- Keep the
.p12file, its password and the private key in a secret manager (AWS Secrets Manager, Azure Key Vault, HashiCorp Vault) or in protected files readable only by the application user. - Never commit the certificate or the key to a repository, and never send them by chat or e-mail.
- Use the certificate only in server-to-server integrations. Never ship it inside a mobile app, a front-end or any software installed on end-user devices.
- Keep the certificate password separate from the certificate file.
- Do not disable server certificate validation (
verify=False,rejectUnauthorized: false,-k) to make the connection work.
Troubleshooting
| Symptom | Likely cause | What to do |
|---|---|---|
TLS handshake error, certificate required, alert handshake failure or connection closed without an HTTP response | The certificate is not being sent | Check that the HTTP client is configured with the certificate and key, as in the examples. |
Error with certificate expired or bad certificate | Expired certificate, or issued for another environment | Check the dates with openssl x509 -noout -dates and use the certificate issued for this environment. |
error:0308010C:digital envelope routines::unsupported or Unsupported PKCS12 PFX data | OpenSSL 3 or Node.js 17+ reading the .p12 file | Convert with the -legacy flag and use the PEM files, as in Step 1. |
Mac verify error: invalid password? | Wrong .p12 password | Check the password received with the certificate. |
unable to set private key file / key values mismatch | Key file does not belong to the certificate, or is still encrypted | Export the key again with -nodes from the same .p12 file. |
401 Unauthorized | The connection passed mTLS; the token or HMAC is invalid | Follow the Auth Token and HMAC Documentation pages. |
Related Documentation
- Authentication API Overview - All authentication layers
- Auth Token - Generate OAuth 2.0 access tokens
- HMAC Documentation - Sign your request bodies
