Language-Specific Authentication Samples
Here you can find some examples to create a token depending on the programming language you are using
Java
package org.example;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
import javax.net.ssl.*;
import java.io.*;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.spec.PKCS8EncodedKeySpec;
public class Main {
public static void main(String[] args) throws Exception {
Certificate caCert = loadFromFile(new File("src/main/resources/ca.pem"));
Certificate publicCert = loadFromFile(new File("src/main/resources/public.crt"));
PrivateKey privateKey = readPKCS8PrivateKey(new File("src/main/resources/private.key"));
KeyStore ks = loadKeyStore(publicCert, privateKey);
TrustManager[] trustManagers = getTrustManagers(getTrustStore(caCert));
KeyManager[] keyManagers = getKeyManagers(ks);
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(keyManagers, trustManagers, new SecureRandom());
HttpClient client = HttpClient.newBuilder().sslContext(sslContext).build();
HttpRequest request = HttpRequest.newBuilder(new URI("https://public-api.mx.clara.com/oauth/token")).header("Authorization", "Basic ==").POST(HttpRequest.BodyPublishers.ofByteArray("".getBytes())).build();//use mx, co, br depending on your country you are based
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status: " + response.statusCode() + " Body: " + response.body());
}
private static Certificate loadFromFile(File file) throws CertificateException, FileNotFoundException {
CertificateFactory fact = CertificateFactory.getInstance("X.509");
return fact.generateCertificate(new FileInputStream(file.getPath()));
}
private static TrustManager[] getTrustManagers(KeyStore trustStore) throws NoSuchAlgorithmException, KeyStoreException {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
return trustManagerFactory.getTrustManagers();
}
private static KeyManager[] getKeyManagers(KeyStore identityStore) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(identityStore, "".toCharArray());
return keyManagerFactory.getKeyManagers();
}
private static KeyStore loadKeyStore(Certificate cert, PrivateKey privateKey) throws KeyStoreException, CertificateException, IOException, NoSuchAlgorithmException {
KeyStore store;
store = KeyStore.getInstance("pkcs12");
store.load(null, "".toCharArray());
store.setKeyEntry("client", privateKey, "".toCharArray(), new Certificate[] { cert });
return store;
}
private static PrivateKey readPKCS8PrivateKey(File file) throws Exception {
Security.addProvider(new BouncyCastleProvider());
try (FileReader keyReader = new FileReader(file); PemReader pemReader = new PemReader(keyReader)) {
PemObject pemObject = pemReader.readPemObject();
byte[] content = pemObject.getContent();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(content);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePrivate(spec);
}
}
private static KeyStore getTrustStore(Certificate caCert) throws CertificateException, IOException, NoSuchAlgorithmException, KeyStoreException {
KeyStore trustStore;
trustStore = KeyStore.getInstance("pkcs12");
trustStore.load(null, "".toCharArray());
trustStore.setCertificateEntry("ca-clara-api", caCert);
return trustStore;
}
}
C#
using System;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace Example
{
class Program
{
static async Task Main(string[] args)
{
//IN CASE OF AN ERROR AS UNKNOW CERTIFICATE YOU HAVE TO ADD THE CA CERTIFICATE IN THE TRUST STORE
//IN MAC WE USE: sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ./ExampleCodeClaraAPI/prod-mx-ca.crt
X509Certificate2 certificate = new X509Certificate2("prod-mx.crt"); //BE SURE THE FILE IS THE FOLDER
using (StreamReader reader = new StreamReader("prod-mx.key")) //BE SURE THE FILE IS THE FOLDER
{
string privateKeyText = await reader.ReadToEndAsync();
RSA privateKey = RSA.Create();
privateKey.ImportFromPem(privateKeyText);
certificate = certificate.CopyWithPrivateKey(privateKey);
}
var clientHandler = new HttpClientHandler();
clientHandler.ClientCertificates.Add(certificate);
clientHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
clientHandler.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
var client = new HttpClient(clientHandler);
var clientId = ""; //CHANGE THIS FOR YOUR CREDENTIALS
var clientSecret = ""; //CHANGE THIS FOR YOUR CREDENTIALS
var base64Credentials = System.Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(clientId + ":" + clientSecret));;
var request = new HttpRequestMessage(HttpMethod.Post, "https://public-api.mx.clara.com/oauth/token"); //WATCH YOUR COUNTRY
request.Headers.Add("Authorization", "Basic " + base64Credentials);
request.Content = new ByteArrayContent(Encoding.UTF8.GetBytes(""));
var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Status: {response.StatusCode}, Body: {responseBody}");
}
}
}
Python 3
import requests
from requests.auth import HTTPBasicAuth
# Configurable Constants
CERT_FILE = "path/to/file/client-public.crt"
KEY_FILE = "path/to/file/client-private.key"
CA_CERT_FILE = "path/to/file/prod-mx-ca.pem"
BASE_URL = "https://public-api.mx.clara.com" # use mx, co, br depending on your country you are based
ENDPOINT = "/api/v2/transactions"
TOKEN_URL = "/oauth/token"
CLIENT_ID = "<get-from-the-json>"
CLIENT_SECRET = "<get-from-the-json>"
def get_access_token():
auth = HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)
try:
response = requests.post(
f"{BASE_URL}{TOKEN_URL}",
auth=auth,
cert=(CERT_FILE, KEY_FILE),
verify=CA_CERT_FILE
)
response.raise_for_status() # Raises an HTTPError for bad responses
token = response.json().get('access_token')
return token
except requests.exceptions.RequestException as e:
print(f"Error fetching access token: {e}")
return None
def get_api_data(access_token):
try:
headers = {'Authorization': f'Bearer {access_token}'}
response = requests.get(
f"{BASE_URL}{ENDPOINT}",
headers=headers,
cert=(CERT_FILE, KEY_FILE),
verify=CA_CERT_FILE
)
response.raise_for_status() # Raises an HTTPError for bad responses
if response.status_code == 200:
data = response.json()
print("API Response:", data)
else:
print("Failed to fetch data. Status code:", response.status_code)
except requests.exceptions.RequestException as e:
print(f"Error fetching API data: {e}")
if __name__ == "__main__":
access_token = get_access_token()
if access_token:
get_api_data(access_token)
Updated 4 months ago