Validate OKTA User and App using Python

Hello, anyone who can help me with python script. I need to validate if user “john.doe@eee.com” is an already existing user in OKTA. And if he is existing, I need to validate if application “Oracle” is already assign to him. If not, I need to assign that application.

Hope you can help me. I am using import request in the script.

Try this

import requests
import json

# Set up the Okta API endpoint and credentials
okta_url = 'https://your-okta-domain.okta.com'
api_token = 'your-okta-api-token'
headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Authorization': f'SSWS {api_token}'
}

# Define the user's email address and the application name
user_email = 'john.doe@eee.com'
app_name = 'Oracle'

# Check if the user exists
response = requests.get(f'{okta_url}/api/v1/users/{user_email}', headers=headers)
if response.status_code == 404:
    print(f'{user_email} is not an existing user in Okta')
    exit()

# Check if the user is assigned to the application
user_id = response.json()['id']
response = requests.get(f'{okta_url}/api/v1/users/{user_id}/appLinks', headers=headers)
app_links = response.json()
app_link = next((al for al in app_links if al['appName'] == app_name), None)
if app_link is not None:
    print(f'{user_email} is already assigned to {app_name}')
    exit()

# Assign the application to the user
app_id = None
response = requests.get(f'{okta_url}/api/v1/apps', headers=headers)
apps = response.json()
app = next((a for a in apps if a['name'] == app_name), None)
if app is not None:
    app_id = app['id']
if app_id is None:
    print(f'{app_name} is not a valid application in Okta')
    exit()

response = requests.post(f'{okta_url}/api/v1/apps/{app_id}/users/{user_id}', headers=headers)
if response.status_code == 204:
    print(f'{user_email} has been assigned to {app_name}')
else:
    print(f'An error occurred while assigning {app_name} to {user_email}')

This script first sets up the Okta API endpoint and credentials using the Okta API token. It then defines the user’s email address and the application name that you want to check.

The script then checks if the user exists in Okta by sending a GET request to the /api/v1/users/{user_email} endpoint. If the user does not exist, the script exits.

If the user exists, the script checks if the user is assigned to the application by sending a GET request to the /api/v1/users/{user_id}/appLinks endpoint. If the user is already assigned to the application, the script exits.

If the user is not assigned to the application, the script looks up the application ID by sending a GET request to the /api/v1/apps endpoint. If the application name is not found, the script exits.

Finally, the script assigns the application to the user by sending a POST request to the /api/v1/apps/{app_id}/users/{user_id} endpoint. If the assignment is successful, the script prints a success message. If an error occurs, the script prints an error message.

4 Likes

Wow thank you Nick, I will try this :slight_smile: Thank you so much!

I just want to know is it the same setup if the scenario is like this -

User - “john.doe@eee.com
Reference Email: "mark.cruz@eee.com

I need to validate if the User is already existing in OKTA. If not, I need to create the account and then use the Reference email as reference on what group I will assign the created user. So the appications under that group will apply on the created user.

Do you have an idea if this is possible? :confused:

Here’s the current script that I have. I used your sample as reference.

Sample data

user_email = ‘juan.lunatest1@aaa.com’
mirror_email = ‘john.doe@aaa.com’
first_name = ‘juan’
last_name = ‘lunatest1’

Check if the user exists

response = requests.get(f’{okta_url}/api/v1/users/{user_email}‘, headers=headers, verify=False)
if response.status_code != 404:
print(f’{user_email} is already an existing user in Okta’)
exit()
else:
print(f’{user_email} account will now be created’)

Account Creation if the user does not exists

body = {
‘profile’: {
‘firstName’: {first_name},
‘lastName’: {last_name},
‘email’: {user_email},
‘login’: {user_email}
}
}

Check the group of Mirror Email

mirror_id = response.json()[‘id’]
response = requests.get(f’{okta_url}/api/v1/users/{mirror_id}/groups’, headers=headers, verify=False)
group = response.json()

Assign the created user to the Mirror Email group

group_id = None
response = requests.get(f’{okta_url}/api/v1/groups’, headers=headers, verify=False)
groups = response.json()

response = requests.post(f’{okta_url}/api/v1/groups/{group_id}/users/{user_email}‘, headers=headers)
if response.status_code == 204:
print(f’{user_email} has been assigned to {group_id}‘)
else:
print(f’An error occurred while assigning {group_id} to {user_email}’)

Seem fine to me.

Following will check the group of the mirror email and assign the created user to a selected group based on group name.

# Check the group of the reference email
mirror_id  = None
response = requests.get(f"{okta_url}/users/{mirror_email}", headers=headers)
if response.status_code == 200:
    mirror_id  = response.json()["id"]
else:
    print(f"Error finding reference user {mirror_email}: {response.text}")
    exit()

response = requests.get(f"{okta_url}/users/{mirror_id }/groups", headers=headers)
if response.status_code != 200:
    print(f"Error finding groups for reference user {mirror_email}: {response.text}")
    exit()

# For assigning one group from mirror
group_id = None
groups = response.json()
for group in groups:
    if group["profile"]["name"] == "Your Group Name Here":
        group_id = group["id"]
        break

if group_id is None:
    print("Could not find group")
    exit()

# Assign the created user to the mirror email group
response = requests.post(f"{okta_url}/groups/{group_id}/users/{user_email}", headers=headers)
if response.status_code != 204:
    print(f"Error assigning user {user_email} to group {group_id}: {response.text}")
    exit()

print(f"{user_email} has been assigned to group {group_id}")

or you can change it to assign all group to the created user.

Thanks for this Nick! It really helped me a lot. One more thing, how can I validate if the user is already assigned to the mirror email group? Is this correct?

response = requests.get(f"{okta_url}/groups/{group_id}/users/{user_email}“, headers=headers, verify=False)
if response.status_code != 204:
print(f”{user_email} not assigned to {group_id}“)
exit()
else:
print(f”{user_email} is now assigned to group {group_id}")
exit()

Thank you

The above code is retrieving all the groups from your mirror account. You can try to make another call to check for your new account group details and check which is missing and add them.

1 Like

Hi Nick, is there a way to get the appname if I only have the label of the application as the details?

For example.
Label: Oracle

I need to get the appname of that label to be able to assign the app to the user. Because the label will not be a valid app in OKTA.

Do I just need to replace “name” with “label”?

app_id = None
responseApp = requests.get(f’{okta_url}/api/v1/apps’, headers=headers, verify=False)
apps = responseApp.json()
app = next((a for a in apps if a[‘name’] == app_name), None)
if app is not None:
app_id = app[‘id’]
if app_id is None:
print(f’{app_name} is not a valid application in Okta’)
exit()

I am not sure what app name you are referring to.

But you can request to filter based on the label with the “q” param in URL.
image

Point to note is that it will return more than one if “q” value is not unique.

For assigning of app to user, have you tried using the App ID from the returned result.

image

1 Like

If i get the apps using link/api/v1/apps, I got this result for example.

“id”: “)i3bfefb3j34444222”,
“name”: “zoomus”,
“label”: “Zoom.us SAML”,
“status”: “ACTIVE”,

However, I only have “Zoom.us SAML” as my details to assign the app. Will the ?q work for this? Because from my testing, I can assign the app and get the app id using the name instead of label.

To give you a full background.

User requested for application “Zoom.us SAML”

Howver, in OKTA the appname is “zoomus” and the label is “Zoom.us SAML”.
How can i get the app id of label “Zoom.us SAML” if in OKTA it is not recognized as valid app since its just a label?

Yes. The q should work. Just make sure that it is URIEncoded.

image

Okay got it and its now working :slight_smile: Thanks Nick

Hey nick, i just want to ask a question with this code. Do I have to make a post script first to create the account before assigning it to the group of the reference mirror email?

Create user

response = requests.post(f’{okta_url}/api/v1/users?activate=false/{user_email}‘, headers=headers, verify=False)
body = {
“profile”: {
“firstName”: {first_name},
“lastName”: {last_name},
“mobilePhone”: “null”,
“secondEmail”: “null”,
“login”: {user_email},
“email”: {user_email},
},
}
if response.status_code != 404:
print(f’{user_email} account is created’)
else:
print(f’Unable to create account for {user_email}')
(exit)
Is this correct? I keep having an error in asigning the user email in the group so I added this script but the account is not created.