Search code examples
pythonjwtdb2db2-luw

Db2 ibm_db (Python): How to connect using a JWT access token?


In the Db2 Python driver the connect API is as follows.

import ibm_db
#use connection string
conn=ibm_db.connect("DATABASE=database;HOSTNAME=hostname;PORT=port;PROTOCOL=TCPIP;UID=username;PWD=password",'','')

What parameters would I need to utilize the token authentication introduced in Db2 LUW 11.5.4?


Solution

  • I had to be on the Db2 client with a minimum of 11.5.4. The connection string needs to have the following JWT- or token-related keywords (found in the list of CLI/ODBC configuration keywords):

    • AUTHENTICATION=TOKEN
    • ACCESSTOKENTYPE=JWT
    • ACCESSTOKEN= with the actual JWT value

    Putting it into action, the following code snippet works to successfully connect using a JWT:

    #!/usr/bin/python3
    import ibm_db, os
    
    # get token from environment    
    TOKEN=os.getenv("TOKEN","invalid")
    connstring="""DATABASE=testdb;HOSTNAME=localhost;PORT=50000;
                  AUTHENTICATION=TOKEN;ACCESSTOKEN={};ACCESSTOKENTYPE=JWT""".format(TOKEN)
    conn=ibm_db.connect(connstring,'','')
    if conn:
        print ("Connection succeeded.")
        ibm_db.close(conn)
    else:
        print("failed")