TLS in Python for JSON DB API

Use TLS in Python for JSON DB API

If you are familiar with the Python Requests library, implementing TLS using private CA TLS certificates for a secure connection is simple. This document also covers the basics of the JSON DB API.

Prerequisites

  • Ensure you have properly enabled TLS and created and configured TLS certificates on the server. See create a server certificate and Enable client certificate authentication. You must create a separate server certificate for each computer that runs a FairCom server. Each FairCom server must be configured to use the appropriate server certificate for the computer on which it runs
  • For client certificate authentication, each username must have a unique client certificate and matching private key. A client certificate allows a client program to identify itself to a FairCom server. Each program that wants to use a certificate must be configured to send the certificate to the server. For this tutorial, we suggest creating a certificate for the "admin" user to avoid user permission configuration. See Use client certificate authentication in client software for setup. 

Do not use a client certificate in a client program to connect to a FairCom server that is not configured with a certificate.

Configure the Python client for TLS

  1. Update your existing POST:
    • Update the "verify" property value to the location of the certificate you obtained for your FairCom server.
    • Update the "cert" property value to the location of your client files.
    • A tuple may be passed to this parameter, where the first element is the client certificate and the second is the separate client private key file.
  1. If you do not already have a JSON DB API project, establish a TLS connection by making the following update to this code.
# JSON.DB TLS with client certificate authentication example
import json
import requests
import urllib3

# Update endpoint, ca_certificate, and client_certs with your specific values.

endpoint = "https://YourServer.YourCompany.com:8443/api"
ca_certificate = "C:/my/certs/ca.crt"
client_certs = "C:/my/certs/clientCertAndKey.pem"
# client_certs = ("C:/my/certs/clientCert.pem", "C:/my/keys/clientKey.pem")

create_session = json.loads( '{"api":"admin","action":"createSession","params":{"username":"none","password":"none"}}' )

login_response = requests.post( endpoint, json = create_session, verify = ca_certificate, cert = client_certs )
  • Set the endpoint to match the Subject Alternate Name in your server certificate.

The name of the endpoint must be one of the Subject Alternative Names in your server certificate. If this is not the case, the server certificate will be rejected.

  • Set the ca_certificate to the public CA certificate for your FairCom server.
  • Set the client_certs to the tuple containing the client certificate file and its private key file.
    • These files must be available on the computer that runs the Python code.
    • The username and password for createSession are ignored while using client Certificate authentication. 
  • Observe the response and make a note of the "authToken" to use in subsequent JSON DB API calls.

 

JSON DB Basics

  1. Retrieve the "authToken" using the following code:
auth_token = login_response.json()['result']['authToken']
  1. Parse the login_response variable and check the "errorCode" property.
    1. "errorCode" with a value of 0 indicates success. "errorCode" with a non-zero value indicates a failure. See Errors and contact FairCom for more information about an error.
  1. Verify that the root object contains a "result" object with an "authToken" property.
  2. List the databases on the server using the following code:
list_databases = json.loads( '{"api":"db","action":"listDatabases","authToken":""}' )
  1. Insert the "authToken" using the following code:
list_databases['authToken'] = auth_token
  1. Send the command using the following function call:
    1. The only change from the request.post() function in Configure the Python client is the variable passed to the "json" parameter and the variable that the response is assigned to. This line is a good target for refactoring into a function that takes the JSON body as a parameter and performs error checking on the response.
list_databases_response = requests.post( endpoint, json = list_databases, verify = server_certificate, cert = client_certs )
  1. Observe the response by using the following code:
print( list_databases_response.json() )

Or for a formatted output use:

print( json.dumps( list_databases_response.json(), indent = 2 ) )
  1. Close the connection using the deleteSession() API call:
delete_session = {"api": "admin", "action": "deleteSession", "authToken": ""}
delete_session_response = requests.post( endpoint, json = delete_session, verify = server_certificate, cert = client_certs )

 

Complete code example

This complete code example has additional error checking.

# JSON.DB TLS with client certificate authentication example
import json
import requests
import urllib3

# Update endpoint, ca_certificate, and client_certs with your specific values.

# "YourServer.YourCompany.com" name must match exactly one of the DNS or IP addesses included in the server's certificate (found in file services.json under listeners.protocol="https".tls.serverCertficateFilename)
endpoint = "https://YourServer.YourCompany.com:8443/api"

# Username and Password are ignored when using client certificate authentication. The username is taken from the client certificate by the server
create_session = json.loads( '{"api":"admin","action":"createSession","params":{"username":"none","password":"none"}}' )

# The ca_certificate must be the same used to sign both the server's certificate and the client certificate.
ca_certificate = "C:/my/certs/ca.crt"

# the CN (CommonName) encoded in the client certificate must match an account on the server (with permissons to run the listDatabases command). This file also includes the matching private Key.
# If the private key is encrypted you will be prompted for the passphrase on each post() when running this program.
client_certs = "C:/my/certs/client.pem"

# If using a separate file for the private key, list it in a tuple after the certificate.
# client_certs = ("C:/my/certs/client.pem", "C:/my/keys/clientKey.pem")

login_response = requests.post( endpoint, json = create_session, verify = ca_certificate, cert = client_certs )

if login_response.status_code != 200:
  print( login_response )
  raise SystemExit( -2 )

print(json.dumps(login_response.json()))
if login_response.json()['errorCode'] != 0:
    raise SystemExit(-3)

print("createSession Successful")

auth_token = login_response.json()['result']['authToken']

list_databases = json.loads( '{"api":"db","action":"listDatabases","authToken":""}' )
list_databases['authToken'] = auth_token
list_databases_response = requests.post( endpoint, json = list_databases, verify = ca_certificate, cert = client_certs )

if list_databases_response.status_code != 200:
  print( list_databases_response )
  raise SystemExit( -4 )
print( json.dumps( list_databases_response.json(), indent = 2 ) )

delete_session = {"api": "admin", "action": "deleteSession", "authToken": ""}
delete_session['authToken'] = auth_token
delete_session_response = requests.post( endpoint, json = delete_session, verify = ca_certificate, cert = client_certs )

if delete_session_response.status_code != 200:
  print( delete_session_response )
  raise SystemExit( -4 )

print("Session Completed")