Okta API: Bulk user creation using Powershell

Skip the blog & Jump to Sample Code

Okta has a very good admin interface which allows to do most of the admin activities. But things can become hectic if you have to do bulk activities like create users, groups, add users to groups etc.

This post is about creating users in bulk using Okta APIs. I am using powershell for scripting but you can use any scripting language for this purpose.

Step 1: Create an API token

Firstly, to use Okta APIs we need an API token. You need to be atleast a Read-Only admin to create new API token. Learn more about Okta Admin roles & Permissions

Below are some key facts to consider when working with Okta API Tokens.

  1. API token are generated with the permissions of the user that created the token. If a user’s permissions changes, then so does that of the token.If the user account is deactivated or deleted then tokens also becomes invalid.Hence, it is recommended to create tokens using a service account.
  2. API tokens are secrets (like passwords) and should be protected.
  3. Tokens are valid for 30 days and automatically renewed every time they are used with an API request.

Login to the Admin Portal of your Okta tenant. Navigate to API token generation page, by clicking Security–> API from the top menu.

Click on Create Token in the API page and provide a name to the API token and later copy the token which appears on the screen. Please note that the token will not be displayed later, so make sure to copy it before closing the dialog.

Step 2: Working with Okta API & PowerShell

Now Okta APIs are a collection of REST APIs and can be easily consumed by any type of client or web application. You can read detailed documentation about the Okta APIs in their documentation. Okta also provides SDKs in almost all major coding platforms.See details here

Now for PowerShell, there is no official SDKs or wrapper modules to work with Okta APIs. So, I am using a unofficial PowerShell wrapper module called Okta-PSModule created by Matt Egan. This module has wrapper functions for almost all operations possible through Okta APIs & is also published in PowerShell gallery which makes it easy to add to your local PowerShell installation.

So, let’s first install the module to the machine. Below command installs it to the logged in user’s Windows Powershell modules. You can remove the scope if you want it to be installed for all users in the machine.

Install-Module OktaAPI -Scope CurrentUser

Now, in my case, I am storing the details of all my users in a CSV file. So, my PowerShell script will be basically reading all the details from the CSV file and then creating the users.

Also, I want all the users to be added to an Okta group, so after creation the script will add the user to the group specified.The CSV file used as input should have following as header column:

login,email, firstName, lastName,password,groupId

#import the OktaAPI module
Import-Module OktaAPI
Connect-Okta "<API Token>" "https://tenant.okta.com"
function Import-BulkUsers($csvPath) {
        $users = Import-Csv $csvPath
        $resultsArray = @()
        foreach ($user in $users) {
            Write-Host "Creating user for"  $user.login
            $profile = @{login = $user.login; email = $user.email; firstName = $user.firstName; lastName = $user.lastName}
            $userCreationStatus = ""
            $groupAssignmentStatus=""
            $ErrorMessage=""
            try {
                if($user.password){
                    # create user with password
                    $oktaUser = New-OktaUser @{profile = $profile; credentials = @{password = @{value = $user.password}}} $true
                }else{
                    # create user without password
                    $oktaUser = New-OktaUser @{profile = $profile} $true
                }
                Write-Host "Created user for"  $user.login -ForegroundColor Green
                $userCreationStatus="Success"
            } catch {
                try {
                    # check if user exists
                    $oktaUser = Get-OktaUser $user.login
                    Write-Host  $user.login " already exists!" -ForegroundColor Yellow
                    $userCreationStatus="Exists"
                } catch {
                    #capture error message
                    $ErrorMessage = $_.Exception.Message
                    $oktaUser = $null
                    $userCreationStatus = "Failed"
                    Write-Host "Failed for "  $user.login -ForegroundColor Red
                }
            }
            if ($oktaUser) {
                try {
                    if($user.groupId){
                        Add-OktaGroupMember $user.groupId $oktaUser.id
                        $groupAssignmentStatus="Success"
                        Write-Host "Add user to group" -ForegroundColor Green
                    }
                } catch {
                    $groupAssignmentStatus = "Failed"
                    $ErrorMessage = $_.Exception.Message
                    Write-Host "Failed adding user to group." -ForegroundColor Red
                }
            }
            $resultsArray += [PSCustomObject]@{
                id=$oktaUser.id;
                firstName= $user.firstName;
                lastName=$user.lastName;
                login = $user.login;
                userCreationStatus = $userCreationStatus;
                groupAssignment= $groupAssignmentStatus;
                ErrorMessage=$ErrorMessage
            }
        }
        $resultsArray | Export-Csv ImportBulkUsers-Result.csv
    }
Import-BulkUsers TestUsers.csv

Now, in the script there are 2 Okta API endpoints used:

  1. Users API – The users API provides many variations while creating users and the sample code above creates user with password & also activates the user. If the password is not provided in the csv file then it will create user without password. In this case, user will receive an activation email from Okta with link to set password.
  2. Groups API : This API is used to assign user to a group. For this we need to have the groups id. This can be fetched from the Admin portal.

Now if you want to expand the code and add more user profile attributes like DisplayName, Division etc, check out the Profile Object to see the full list of available attributes. You can also have custom profile properties in the profile object.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s