Skip to main content

Authentication test

1. Introduction and Initial Configuration

Overview

This documentation details the process of signing and encrypting headers for secure authentication in requests to our API. The process ensures that requests are reliable and secure, preventing unauthorized access and ensuring data integrity.

Import libraries

Here, we import the necessary libraries throughout the authentication process.

import json
import requests
from datetime import datetime
from hashlib import md5
from jose import jwt

Define variables

We will use the variables base_url, endpoint, method, and request_body. In this example, we will make a POST request to the "/test" endpoint.

base_url = "https://api-auth.sandbox.qitech.app"
endpoint = "/test"
method = "POST"
request_body = {"name": "QI Tech"}

2. Data Preparation for Signature

Insert encryption data

The keys in this example are for demonstration purposes only. Please use your own keys.

api_key = "f19c6e62-bd82-4334-9839-020810550c44" 

client_private_key = '''-----BEGIN EC PRIVATE KEY-----
MIHbAgEBBEHh1hIeOPE5XNNhn6bxRAmVswsPZ0wZCmzVvP8Tl/LZK9ofVmRVGzll
srU1uezJEyHKYdOHrE2p52xUj+pHzjJvb6AHBgUrgQQAI6GBiQOBhgAEAAofUz1J
hBSOyGHLsnV9Sz0DSWmhl7U+ljqbfa8PKVFWSV3w16I1v2zME5/UzUhHn1gWsjnv
7/ekcLLAQbvqMPNXAfjIhFXLAPzqbB9iCuVua1v0Vgy52rBemOWrJka/Ws2bnKR8
h1N1OxOYeYr6C2jqMygBLktKMAs+282CEiEb4bIv
-----END EC PRIVATE KEY-----'''

Format date

The date and time object provided must be in UTC and must follow the ISO 8601 international standard ("2023-06-26T19:48:32.759844Z").

timestamp = datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%fZ")

Define JWT header

We define the JWT encoding algorithm

jwt_header = {
"typ": "JWT",
"alg": "ES512"
}

Build MD5 hash for JSON header signature

Build MD5 hash for header signature using the payload

json_body = json.dumps(request_body)
md5_hash = md5(json_body.encode()).hexdigest()
Attention!

The MD5 hash for GET and DELETE requests must be generated with an empty payload

Build an MD5 hash for the header signature File

Build an MD5 hash for the header signature using a file

md5_instance = md5()
for chunk in iter(lambda: file.read(4096), b""):
md5_instance.update(chunk)

file.seek(0)
md5_hash = md5_instance.hexdigest()

Define the JWT body

These are the necessary pieces of information to sign the header

jwt_body = {
"payload_md5": md5_hash,
"timestamp": timestamp,
"method": method,
"uri": endpoint
}

Encrypt the header

encoded_header_token = jwt.encode(
claims=jwt_body,
key=client_private_key,
algorithm="ES512",
headers=jwt_header
)

Build signed header

signed_header = {
"AUTHORIZATION": encoded_header_token,
"API-CLIENT-KEY": api_key
}

Build the request URL

url = f"{base_url}{endpoint}"

3. Make the Request

post_test_response = requests.post(url=url, headers=signed_header, json=request_body)