Unnie Ayilliath

Microsoft 365 | Azure | Identity Solutions

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 OktaAPI created by Gabriel Sroka. 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.

Published by

21 responses to “Okta API: Bulk user creation using Powershell”

  1. Gabriel Sroka Avatar

    Hi
    Thanks for the post.

    You mentioned Matt Egan and his PowerShell module, but you used mine: https://github.com/gabrielsroka/OktaAPI.psm1

    His is very good, too!

    1. Am extremely sorry, I misquoted your contribution to someone else. I was trying both the modules at the same time and found your’s better. But while blogging by mistake gave the credit to the other module. Thanks for correcting me.

  2. Gabriel Sroka Avatar

    Hi again.

    It’s no problem. Thanks for fixing it. Would you please also change the link from Matt’s site to mine and my name to “Gabriel Sroka”.

    Thanks.

  3. The status of the user is not Active. It is “Pending User Action” always.
    It requires email confirmation.

    1. Yes, that is the default status if you create an account without password. User will receive an email with link to activate their account. they have to set password while they activate.

  4. Hey, I’m trying out this script to generate a list of users in my Okta dev instance, and getting errors in the user generation. The Error Messages shows a 405 Method Not Allowed. Has something been changed on the API side that prevents this working now, or am I missing something still? Thanks!

  5. Hey, I’m trying out this script to generate a list of users in my Okta dev instance, and getting errors in the user generation. The Error Messages shows a 405 Method Not Allowed. Has something been changed on the API side that prevents this working now, or am I missing something still? Thanks!

    1. Hello, not that I am aware of . I would suggest to check the github page for the powershell module

  6. […] Okta API: Creación masiva de usuarios usando Powershell – Unnie… […]

  7. Hi, I’m just trying to narrow your script to the point where I can import a CSV of existing Okta users and add them to a specific existing group. How is this possible, I keep getting numerous errors. CSV file has okta emails (usernames) and 2nd column with group ID, maybe there is an easier/simpler way.

    Trying:

    $users = Import-Csv c:\temp\scripts\”oktausers1.csv”
    foreach ($user in $users) {Add-OktaGroupMember $group.id $user.id}

    Thank you for your time,
    Joel

    1. Hi Joel, with the OktaAPI module it should be failry easy. You can use Get-OktaUsers command, it returns list if users in batch of 200. You can see below sample code:

      function Export-Users() {
      $totalUsers = 0
      $exportedUsers = @()
      # for more filters, see https://developer.okta.com/docs/api/resources/users#list-users-with-a-filter
      $params = @{} # @{filter = ‘status eq “ACTIVE”‘}
      do {
      $page = Get-OktaUsers @params
      $users = $page.objects
      foreach ($user in $users) {
      $exportedUsers += [PSCustomObject]@{id = $user.id; login = $user.profile.login}
      }
      $totalUsers += $users.count
      Write-Host “$totalUsers users”
      $params = @{url = $page.nextUrl}
      } while ($page.nextUrl)
      $exportedUsers | Export-Csv exportedUsers.csv -notype
      Write-Host “$totalUsers users exported.”
      Write-Host “Done.”
      }

      Source: https://github.com/gabrielsroka/OktaAPI.psm1/blob/master/CallOktaAPI.ps1

      1. Hi Unnie,

        Thanks for the reply. To clarify, I don’t want to pull users from the API, but want to see if its possible to take specific list of existing Okta users stored in CSV, import it, and then assign all those users to a specific Okta group. Is this possible? I need to do this since there is no way in the Okta admin UI to add users in bulk (or by CSV) to a specific group. You can only do this CSV import in the UI for the application, which we don’t normally do.

        So if the ask to you was (build a process to import a CSV of existing users and assign them to a single group), that is what I’m trying to identify. Would appreciate any feedback or time you have to look at this, but understanding this is just free advise 🙂

        Thank you!
        Joel

  8. You can use Import-Users method in the sample as starting point. Edit it to satisfy your needs. Sample => https://github.com/gabrielsroka/OktaAPI.psm1/blob/master/CallOktaAPI.ps1

    1. Hi
      can we update okta bulk users custom attributes from csv file using power shell?

  9. Hi
    can we update okta bulk users custom attributes from csv file using power shell?

  10. Hi , Can we update bulk user profiles from csv using powershell ?

  11. This script is working well for me when loading 30-50 new users a week which has improved our work flow. However, how do we impliment a temp password instead so on first login the user is forced to change their password? I have been reading about nextLogin=changepassword but having issues plugging this in. Any help is appreciated, thanks.

    1. Hi Dmitri,
      In the csb you can have a password column and set some arbitrary password. The code in the blog has a section which does that.
      # create user with password
      $oktaUser = New-OktaUser @{profile = $profile; credentials = @{password = @{value = $user.password}}} $true

  12. Hi Unnie,

    The script worked well for me, totally life saving while our company is acquiring hundreds of employees. I’ve had to change computers and having to setup my new environment. When I’m trying to run the script now I get “The remote server returned an error: (404) Not Found” error code in the output csv. I’ve recreated my API key and made sure TLS 1.2 was enabled within powershell. Do you have any advice?

    1. Hi Adm, did you manage to get it fixed. 404 might be that your tenant url is wrong or some n/w element is blocking the requests.

Leave a comment

Website Powered by WordPress.com.