💥 Language-Specific Authentication Samples
Here you can find some examples to create a token depending on the programming language you are using
⚡Java
package com.clara.integrations.claraapi.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;
import java.util.Base64;
public class Main {
public static void main(String[] args) throws Exception {
Certificate publicCert = loadFromFile(new File("path-to-your-certificate.crt"));
PrivateKey privateKey = readPKCS8PrivateKey(new File("path-to-your-certificate.crt.key"));
KeyStore ks = loadKeyStore(publicCert, privateKey);
TrustManager[] trustManagers = getTrustManagers();
KeyManager[] keyManagers = getKeyManagers(ks);
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(keyManagers, trustManagers, new SecureRandom());
String clientId = "YOUR-CLIENT-ID";
String clientSecret = "YOUR-CLIENT-SECRET";
String auth = clientId + ":" + clientSecret;
String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());
HttpClient client = HttpClient.newBuilder().sslContext(sslContext).build();
HttpRequest request = HttpRequest.newBuilder(new URI("https://public-api.mx.clara.com/oauth/token")).header("Authorization", "Basic " + encodedAuth).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() throws NoSuchAlgorithmException, KeyStoreException {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
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);
}
}
}
⚡C# - Windows
Note: The Windows platform does not support CRT or PEM files directly in .NET, so you need to convert them into a PFX file. You can do this by running the following command in your terminal using the OpenSSL tool, while generating the file you will be asked to create a password, you can choose a password in this step to be used in your code after.
openssl pkcs12 -export -out certificate.pfx -inkey certificate.key -in certificate.crt
Another step is installing the PEM file into the Trusted Root Certification Authorities. In case this file is not being recognized by the Certificate Manager, change its extension to crt and install it on the Local Machine.
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)
{
X509Certificate2 certificate = new X509Certificate2("prod-mx.pfx", "your-password"); //BE SURE THE FILE IS THE FOLDER
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}");
}
}
}
⚡C# - macOs or Linux
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)
{
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.adapters import HTTPAdapter
from urllib3.util.ssl_ import create_urllib3_context
import base64
class SSLAdapter(HTTPAdapter):
def __init__(self, certfile, keyfile, cafile):
self.context = create_urllib3_context()
self.context.load_cert_chain(certfile, keyfile)
self.context.load_verify_locations(cafile)
super().__init__()
def init_poolmanager(self, *args, **kwargs):
kwargs['ssl_context'] = self.context
return super().init_poolmanager(*args, **kwargs)
client_id = 'YOUR-CLIENT-ID'
client_secret = 'YOUR-CLIENT-SECRET'
auth = base64.b64encode(f"{client_id}:{client_secret}".encode()).decode()
session = requests.Session()
session.mount("https://", SSLAdapter("path-to-your-certificate.crt", "path-to-your-certificate.crt.key", "path-to-ca-cert.pem"))
headers = {
"Authorization": f"Basic {auth}"
}
response = session.post("https://public-api.mx.clara.com/oauth/token", headers=headers)
print(f"Status: {response.status_code} Body: {response.text}")
⚡Go
package main
import (
"crypto/tls"
"crypto/x509"
"encoding/base64"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
)
func main() {
cert, err := tls.LoadX509KeyPair("path-to-your-certificate.crt", "path-to-your-certificate.crt.key")
if err != nil {
log.Fatalf("failed to load client cert: %v", err)
}
caCert, err := ioutil.ReadFile("path-to-ca-cert.pem")
if err != nil {
log.Fatalf("failed to load CA cert: %v", err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: caCertPool,
}
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
},
}
clientID := "YOUR-CLIENT-ID"
clientSecret := "YOUR-CLIENT-SECRET"
auth := base64.StdEncoding.EncodeToString([]byte(clientID + ":" + clientSecret))
req, err := http.NewRequest("POST", "https://public-api.mx.clara.com/oauth/token", nil)
if err != nil {
log.Fatal(err)
}
req.Header.Add("Authorization", "Basic "+auth)
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Printf("Status: %s Body: %s\n", resp.Status, string(body))
}
⚡JavaScript/Node.Js
const https = require('https');
const fs = require('fs');
const path = require('path');
const clientId = 'YOUR-CLIENT-ID';
const clientSecret = 'YOUR-CLIENT-SECRET';
const auth = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
const options = {
hostname: 'public-api.mx.clara.com',
port: 443,
path: '/oauth/token',
method: 'POST',
key: fs.readFileSync('path-to-your-certificate.crt.key'),
cert: fs.readFileSync('path-to-your-certificate.crt'),
ca: fs.readFileSync('path-to-ca-cert.pem'),
headers: {
'Authorization': `Basic ${auth}`
}
};
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => { data += chunk; });
res.on('end', () => {
console.log(`Status: ${res.statusCode} Body: ${data}`);
});
});
req.on('error', (e) => {
console.error(e);
});
req.end();
Updated about 17 hours ago