Monday, March 1, 2021

JWT token authentication in Db2 runtimes like Python or Node.js

Python script connecting to Db2 with JWT
Some weeks ago I discussed how to configure JWT-based token authentication in Db2. I set up Db2 to accept JWS identity tokens and then connected to my test database using the command line. But how do you connect from a programming language like Python or Node.js? Here is what I needed.

Have the right Db2 client version

Token authentication was introduced in Db2 11.5 Mod Pack 4 ("11.5.4"). In order to successfully connect using a JWT you need to be on a recent client level. Thus, I had to install the 11.5 Mod Pack 5 fixpack. If you are not on the required client level, the additional keywords are not recognized and you will see error messages such as "password missing" (SQL30082N, RC 3).

Know the right keywords

The Db2 documentation has all the required information on how to make use of token authentication - but not in a single place. Thus, it required some search and mentally piecing it together. A good source was the list of Db2 CLI / ODBC configuration keywords. With that I was able to answer my question on how to connect using the ibm_db Python driver. I had to pass the following keywords:

  • ACCESSTOKEN=the actual JWT value

Sample script:

import ibm_db, os

# get token from environment    
"".format(TOKEN) conn=ibm_db.connect(connstring,'','') if conn: print ("Connection succeeded.") ibm_db.close(conn) else: print("failed")

As you can see, I am not passing in any user ID or password, but the set AUTHENTICATION to TOKEN. In addition, similar to the command line example, I pass in the token type and the actual token. Because the Db2 open source drivers all depend on the CLI / ODBC driver, configuration for Node.js, Golang, Ruby and Rust is similar.

If you have feedback, suggestions, or questions about this post, please reach out to me on Twitter (@data_henrik) or LinkedIn.