Authenticating REST commands in Db2

Some values that are required to authenticate REST calls are pre-specified in the Db2® REST implementation on Cloud Pak for Data, but you must pass some values when authenticating or the request is rejected.

All REST calls require an authentication token to confirm the identity of the issuer. If you are authenticating against the Cloud Pak for Data database instance in the cluster that the REST service belongs to, you do not need to specify valid values for dbHost, dbName and dbPort. These values are pre-specified. For dbHost and dbName, if you pass empty strings, the pre-specified values are used. For dbPort, if you pass -1, the pre-specified values are used. You need to pass True for isSSLConnection to leverage the pre-specified values.

If you wish to authenticate with a different database instance, you can specify the parameters for that database instance as necessary.

Note: This topic illustrates how to authenticate a REST command using Python. You can follow a similar procedure when using other programming languages such as Curl, Perl, or JavaScript.

To request a token, issue the following statements:

from pprint import pprint
import requests
from requests import Response

token = ""

#These values should be updated with the Db2 REST HOST/PORT from the https://www.ibm.com/docs/SSQNUZ_4.5.x/svc-db2/db2-rest-endpoint.html topic
restHostname = "rest_hostname"
restPort = "443"

#These values must be specified base on your database instance
username = "username"
password = "password"

#These values can be left unchanged to authenticate in a Cloud Pak for Data instance.
#If authenticating with a different database instance these values must be specified 
dbHostname = ""
dbName = ""
dbPort = -1

def authenticate():
    global token
    url = "https://%s:%s/v1/auth"% (restHostname, restPort)
    json = {
        "dbParms": {
            "dbHost": dbHostname,
            "dbName": dbName,
            "dbPort": dbPort,
            "isSSLConnection": True,
            "username": username,
            "password": password,
        },
        "expiryTime": "24h"
    }
    response = requests.post(url, verify = False, json = json, proxies = None)
    if response.status_code == 200:
        token = response.json()["token"]
        print("Authenticated user with token:", token)
    else:
      print("Authentication failed")
      print(response.status_code, response.reason)

The token is provided in the response. All subsequent calls require the token to be specified in their headers:

headers = {
        "content-type": "application/json",
        "authorization:" token
    }

A token is valid until it expires (the expiry time is specified by the expiryTime parameter in the request), or until the REST server is restarted.