Accessing The Okta API using Python
Okta is a cloud PaaS platform for Identity Management which offers a number of SDKs to work with the platform, amongst them a Python SDK.
A small part of most identity projects is the need for small maintenance, migration and reporting tasks; the little stuff. the Python scripting language can be a great way to get these often ad-hoc tasks completed efficiently.
In this article, the very simple task of producing a TSV format spreadsheet containing users’ Okta IDs together with their last names is accomplished with the Python 3 language.
The first thing to do is to install the Okta SDK into your Python 3 environment;
pip3 install okta
Now it is possible to generate the report with a script such as this;
import asyncio
import os
import string
from okta.client import Client as OktaClient
async def main(okta_client):
template = string.Template("""${id}\t${status}\t${last_name}""")
print(template.substitute({
'id': 'id',
'status': 'status',
'last_name': 'last-name'
}))
def render_user(user):
print(template.substitute({
'id': user.id,
'status': str(user.status.name),
'last_name': user.profile.lastName
}));
params = {'search': 'status eq "ACTIVE" or status eq "SUSPENDED"',
'sortBy': 'profile.lastName',
'sortOrder': 'asc'}
users, resp, err = await okta_client.list_users(query_params=params)
while True:
if err is not None:
raise Exception('an issue has arisen fetching the users; ' + str(err))
for u in users:
render_user(u)
if not resp.has_next():
break;
users, err = await resp.next()
config = {
'orgUrl': os.environ['OKTA_ORG_URL'],
'token': os.environ['OKTA_API_TOKEN']
}
loop = asyncio.get_event_loop()
loop.run_until_complete(main(OktaClient(config)))
This is using the Okta List Users API.
To access any of the Okta APIs from a script like this, you will need to obtain a token.
In an environment such as Linux or Mac, this script can be executed with a command such as;
OKTA_ORG_URL=https://xyz.okta.org/ OKTA_API_TOKEN=XXXXX python3 -u ./script.py
This demonstrates how easy it is to combine the flexibility of the Python language with the Okta platform.