Skip to main content

Authentication test

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.

Atenção!

The GET and DELETE methods hash md5 must be generated with an empty payload

#Here, we import the necessary libraries throughout the authentication process.
from jose import jwt
import json
from datetime import datetime
from hashlib import md5
import requests

def get_auth_header(endpoint, method, CLIENT_PRIVATE_KEY, API_KEY, request_body=None):

if request_body is None:
request_body = {}

#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.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%fZ")

#We define the JWT encoding algorithm
jwt_header = {
"typ": "JWT",
"alg": "ES512"
}

#Build MD5 hash for header signature using the payload
json_body = json.dumps(request_body)
md5_hash = md5(json_body.encode()).hexdigest()

#Define the JWT body
jwt_body = {
"payload_md5": md5_hash,
"timestamp": timestamp,
"method": method,
"uri": endpoint
}

#Build signed 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
}

return signed_header


if __name__ == "__main__":

#we will use the following variables base_url, endpoint, method and request_body. In this example, we will be conducting a POST in /test.
#The following keys in this example are fake. Please use your own keys.
CLIENT_PRIVATE_KEY = "Your Private Key Here"
API_KEY = "Your API Key Here"

BASE_URL = "https://api-auth.sandbox.qitech.app"
METHOD = "POST" #GET ou POST
REQUEST_BODY = {
"name": "QI Tech"
}

#In order to conduct a GET requisition in /test, it is necessary to insert the API Key into the endpoint, while for a post requisition, it is not.
if METHOD == 'GET':
ENDPOINT = f"/test/{API_KEY}"
signed_header = get_auth_header(ENDPOINT, METHOD, CLIENT_PRIVATE_KEY, API_KEY)
response = requests.get(f"{BASE_URL}{ENDPOINT}", headers=signed_header)
else:
ENDPOINT = f"/test/"
signed_header = get_auth_header(ENDPOINT, METHOD, CLIENT_PRIVATE_KEY, API_KEY, REQUEST_BODY)
response = requests.post(f"{BASE_URL}{ENDPOINT}", json=REQUEST_BODY, headers=signed_header)

print(response.status_code)
print(response.json())