Skip to content

Powershell CLI for communicating with the Okta API

License

Notifications You must be signed in to change notification settings

okta/okta-powershell-cli

Repository files navigation

Okta.PowerShell - The PowerShell module for the Okta Management API

This repository contains the Okta management PowerShell module. This PowerShell module can be used to easily interact with the Okta management API and:

Note: For more details about the APIs and models the SDK support, check out the API docs

Release status

This library uses semantic versioning and follows Okta's library version policy.

Version Status
1.x ✔️ Stable

The latest release can always be found on the releases page. For more information about our SDKs' lifecycle, check out our docs.

Need help?

If you run into problems using the Okta PowerShell module, you can

Getting started

This PowerShell module is automatically generated by the OpenAPI Generator project:

  • API version: 3.0.0
  • SDK version: 1.0.0
  • Build package: org.openapitools.codegen.languages.PowerShellClientCodegen For more information, please visit https://developer.okta.com/

The Okta PowerShell module is compatible with:

  • PowerShell 6.2 or later
  • Mac/Windows
  • OIE and Classic Okta orgs

Installation

PSGallery

To install the Okta.PowerShell module from PS Gallery run the following command:

Install-Module -Name Okta.PowerShell -RequiredVersion <MODULE_VERSION>

To verify the module was successfully installed, run Get-InstalledModule -Name 'okta.powershell' and verify that the module information is shown.

To uninstall the module, simply run:

Uninstall-Module -Name Okta.PowerShell

Chocolatey

To install the Okta.PowerShell module from Chocolatey run the following command:

choco install okta.powershell --version=<MODULE_VERSION>

To verify the module was successfully installed, run choco list "okta.powershell" and verify that the module information is shown.

To uninstall the module, simply run:

choco uninstall okta.powershell

GitHub

Note: Signed binary releases are posted to the okta-powershell-cli releases section in Github.

To install from the source, run the following command to build and install the PowerShell module locally:

./Build.ps1
Import-Module -Name '.\src\Okta.PowerShell' -Verbose

To avoid function name collision, one can use -Prefix, e.g. Import-Module -Name '.\src\Okta.PowerShell' -Prefix prefix

To uninstall the module, simply run:

Remove-Module -FullyQualifiedName @{ModuleName = "Okta.PowerShell"; ModuleVersion = "<MODULE_VERSION>"}

Tests

To install and run Pester, please execute the following commands in the terminal:

Install-module -name Pester -force

Invoke-Pester

For troubleshooting, please run $DebugPreference = 'Continue' to turn on debugging and disable it with $DebugPreference = 'SilentlyContinue' when done with the troubleshooting.

Security recommendations

We recommend limiting the access permissions of your Okta.PowerShell scripts to only authorized users.

Add the appropriate users or groups and assign the necessary permissions to the OktaConfiguration.ps1 file (Full Control, Read & Execute, etc.), and remove any unnecessary users or groups from the list.

:Warning: The OktaConfiguration.ps1 file contains secrets, so we recommend using least privilege access to the configuration file.

Note: For more information about PowerShell script security, check out the official PowerShell security guide.

Usage guide

Prerequisites

The PowerShell module uses the device authorization flow to obtain an access token, so it requires, at least, three configuration values. These are the values for the Okta Org domain, the client ID of the OIDC Native Application and the scope for the API grants you are going to need. For example, if you are going to get groups then you will need the grant okta.groups.read configured in your scope. Make sure to assign the application to anyone that needs access to it.

non-admin users

Non-admin users will require to be granted specific permissions to perform certain tasks and access resources.

Check out the following resources to learn more:

Set your configuration and execute commands

  1. Set your configuration
$Configuration = Get-OktaConfiguration
$Configuration.BaseUrl = 'https://myorg.okta.com'
$Configuration.ClientId = 'MY_CLIENT_ID'
$Configuration.Scope = "okta.groups.read" # or "okta.groups.read okta.apps.read"
  1. Authorize your device
Invoke-OktaEstablishAccessToken

Note: You have to open the browser and navigate to the provided URL to complete the flow. Once the device is authorized, go back to the PowerShell terminal.

  1. Invoke commands
Invoke-OktaListGroups

id                    : 00g9erf7s3ydK79IX5d7
created               : 5/5/23 1:45:05 PM
lastUpdated           : 5/5/23 1:45:05 PM
lastMembershipUpdated : 5/5/23 1:45:05 PM
objectClass           : {okta:user_group}
type                  : OKTA_GROUP
profile               : @{name=Sales; description=}
_links                : @{logo=System.Object[]; users=; apps=}

Note: For more details about commands, check out the documentation for API endpoints

Note: If you want to remove the access token from configuration you can execute Invoke-OktaRemoveAccessToken

Configure a proxy

$proxyUrl = "http://127.0.0.1:8888"
$webProxy = New-Object System.Net.WebProxy($proxyUrl)
$Configuration.Proxy = $webProxy

Create objects

The Okta PowerShell Module supports two approaches for object creation:

  1. The "Initialize-Object" command
  2. Using PowerShell's native PSCustomObject for creating objects

Create the object manually using PowerShell's native PSCustomObject and the API reference

You can check out the API reference to explore what the payload structure should look like for the operation you want to perform. For example, if you want to create a group, check out the Add Group API reference and look for the request sample. For this particular operation, you will see that the payload should look like the following:

{
    "profile": {
        "description": "All users West of The Rockies",
        "name": "West Coast users"
    }
}

Then you can recreate the same payload using PSCustomObject:

$Group = [PSCustomObject]@{ 
            profile = [PSCustomObject]@{
                description = "All users West of the Rockies"
                name = "West Coast users"}
    }

$NewGroup = New-OktaGroup -Group $Group

⚠️ If you follow this approach, you have to ensure the casing is correct. Notice that for this particular operation, all the properties of the group payload are in lowercase.

Create the object using "Initialize-Object" command

The Okta PowerShell Module provides an "Initialize-Object" command that simplifies the creation and initialization of most of the objects. Each object represents a distinct entity supported by the Okta PowerShell Module, and this command provides a standardized approach to create and configure these objects.

Following the same "Create group" example as in the previous step, you can create a group object by executing the corresponding "Initialize-Object" commands:

$GroupProfile = Initialize-OktaGroupProfile -Name "West Coast users" -Description "All users West of the Rockies"
$Group = Initialize-OktaGroup -VarProfile $GroupProfile
$NewGroup = New-OktaGroup -Group $Group

Notice that for objects that have nested properties, each nested property may itself be an object that needs to be initialized separately. In such cases make sure to:

  1. Initialize each nested property individually.
  2. Pass the nested object(s) as part of the -Property parameter when initializing the parent object.

Always verify the required structure and types for nested properties by consulting the API reference.

Get a user

$User = Get-OktaUser -UserId "foo"

Create a user

$UserProfile = [PSCustomObject]@{
                firstName = 'John'
                lastName = 'Doe'
                login = 'john.doe@mail.com'
                email = 'john.doe@mail.com'
            }

$CreateUserRequest = Initialize-OktaCreateUserRequest -VarProfile $UserProfile -GroupIds 'foo'
$TestResult = New-OktaUser -Body $CreateUserRequest

Note: If you initialize objects using PSCustomObject, ensure the casing is correct.

Create a user with password

$UserProfile = [PSCustomObject]@{
                firstName = 'John'
                lastName = 'Doe'
                login = 'john.doe@mail.com'
                email = 'john.doe@mail.com'
            }

$UserCredentials = [PSCustomObject]@{ 
                    password = [PSCustomObject]@{ value = 'Hell0W0rld'} 
                }

$CreateUserRequest = Initialize-OktaCreateUserRequest -VarProfile $UserProfile -Credentials $UserCredentials
$TestResult = New-OktaUser -Body $CreateUserRequest

Note: If you initialize objects using PSCustomObject, ensure the casing is correct.

Alternatively, you can use the Initialize commands to create the user payload:

$UserProfile = Initialize-OktaUserProfile -Email "joe.doe@mail.com" -Login "joe.doe@mail.com" -FirstName "Joe" -LastName "Doe"
$UserCredentials = Initialize-OktaUserCredentials -Password "Hell0W0rld!"

$CreateUserRequest = Initialize-OktaCreateUserRequest -VarProfile $UserProfile -Credentials $UserCredentials
$TestResult = New-OktaUser -Body $CreateUserRequest

List users with pagination

$Users  = Invoke-OktaListUsers -Limit 10 

Utilize the -withHttpInfo flag to retrieve additional response properties, including NextPageUri for accessing the subsequent page of results. Additionally, you can seamlessly access all response headers through the Headers property.

To paginate results, use Uri param, which allows passing absolute URIs:

$UsersResponse  = Invoke-OktaListUsers -Limit 10 -withHttpInfo

While ($UsersResponse.NextPageUri)
{
    $UsersResponse = Invoke-OktaListUsers -Uri $UsersResponse.NextPageUri  -withHttpInfo #This time you can pass the absolute Uri with already contains query params such as "limit" or/and "after"
    $UsersList =  $UsersResponse.Response
}

Create an application

$OAuthClient = [PSCustomObject]@{
                client_uri = "https://example.com/client"
                logo_uri = "https://example.com/assets/images/logo-new.png"
                response_types = @("token", "id_token", "code")
                redirect_uris = @("https://example.com/oauth2/callback", "myapp://callback")
                post_logout_redirect_uris = @("https://example.com/postlogout", "myapp://postlogoutcallback")
                grant_types = @("implicit", "authorization_code")
                application_type = "native"
                tos_uri = "https://example.com/client/tos"
                policy_uri = "https://example.com/client/policy"
            }
# a simple test to create an object
$Settings = Initialize-OktaOpenIdConnectApplicationSettings -OauthClient $OAuthClient

$NewApp = Initialize-OktaOpenIdConnectApplication -Label "New App" -SignOnMode "OPENID_CONNECT" -Settings $Settings

Note: If you initialize objects using PSCustomObject, ensure the casing is correct.

Note: Null values are removed from the payload by default. If you want to include null values you have to include the -IncludeNullValues flag.

Note: For more API samples checkout our tests

Get logs

Since the System Log API requires since and until query params to be ISO 8601 compliant timestamp, make sure to format dates accordingly:

$since = (Get-Date).AddMonths(-6).ToString("yyyy-MM-ddTHH:mm:ssZ")
$until = (Get-Date).ToString("yyyy-MM-ddTHH:mm:ssZ")
Get-OktaLogs -since $since -until $until

Rate Limiting

The Okta API will return 429 responses if too many requests are made within a given time. Please see Rate Limiting at Okta for a complete list of which endpoints are rate limited. When a 429 error is received, the X-Rate-Limit-Reset header will tell you the time at which you can retry. This section discusses methods for handling rate limiting with this SDK.

Built-In Retry

The Okta.PowerShell module uses a built-in retry strategy to automatically retry on 429 errors.

You can configure the following options when using the built-in retry strategy:

Configuration Option Description
RequestTimeout The waiting time in milliseconds for a request to be resolved by the client. Less than or equal to 0 means "no timeout". The default value is $null (None).
MaxRetries The number of times to retry.

Usage

$Config = Get-OktaConfiguration
$Config.MaxRetries = 2
$Config.RequestTimeout = 6000 

# Invoke your commands as usual
$Result = Invoke-OktaListApplications 

Note: We're happy to accept contributions and PRs! Please see the contribution guide to understand how to structure a contribution.