CallOktaAPI.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
#Requires -Module OktaAPI
Import-Module OktaAPI

# $token comes from Okta Admin > Security > API > Tokens > Create Token
# see https://developer.okta.com/docs/api/getting_started/getting_a_token

# Call Connect-Okta before calling Okta API functions. Replace YOUR_API_TOKEN and YOUR_ORG with your values.
# Connect-Okta "YOUR_API_TOKEN" "https://YOUR_ORG.oktapreview.com"
# Or place the Connect-Okta call in OktaAPISettings.ps1
.\OktaAPISettings.ps1

# This file contains functions with sample code. To use one, call it.

# Apps

function Add-SwaApp() {
    $user = Get-OktaUser "me"
    
    # see https://developer.okta.com/docs/api/resources/apps#add-custom-swa-application
    $app = @{
        label = "AAA Test App"
        settings = @{
            signOn = @{loginUrl = "https://aaatest.oktapreview.com"}
        }
        signOnMode = "AUTO_LOGIN"
        visibility = @{autoSubmitToolbar = $false}
    }
    $app = New-OktaApp $app

    # see https://developer.okta.com/docs/api/resources/apps#assign-user-to-application-for-sso
    $appuser = @{id = $user.id; scope = "USER"}
    Add-OktaAppUser $app.id $appuser
}

function Add-AppUser() {
    $app = Get-OktaApp "?q=A bookmark app"
    $user = Get-OktaUser "me"
    $appuser = @{id = $user.id; scope = "USER"}
    $appuser = Add-OktaAppUser $app.id $appuser
}

function Get-AllMyApps() {
    $user = Get-OktaUser "me"

    $totalApps = 0
    $params = @{filter = "user.id eq `"$($user.id)`""}
    do {
        $page = Get-OktaApps @params
        $apps = $page.objects
        foreach ($app in $apps) {
            Write-Host $app.id $app.label
        }
        $totalApps += $apps.count
        $params = @{url = $page.nextUrl}
    } while ($page.nextUrl)
    "$totalApps apps found."
}

function Get-PagedAppUsers($appid) {
    $totalAppUsers = 0
    $params = @{appid = $appid}
    do {
        $page = Get-OktaAppUsers @params
        $appusers = $page.objects
        foreach ($appuser in $appusers) {
            Write-Host $appuser.credentials.userName
        }
        $totalAppUsers += $appusers.count
        $params = @{url = $page.nextUrl}
    } while ($page.nextUrl)
    "$totalAppUsers app users found."
}

function Get-AppGroups($appid) {
    $total = 0
    $params = @{appid = $appid}
    do {
        $page = Get-OktaAppGroups @params
        $appgroups = $page.objects
        foreach ($appgroup in $appgroups) {
            $group = Get-OktaGroup $appgroup.id
            $licenses = $appgroup.profile.licenses -join ";"
            Write-Host $appgroup.id "," $group.profile.name "," $licenses
        }
        $total += $appgroups.count
        $params = @{url = $page.nextUrl}
    } while ($page.nextUrl)
    "$total app groups found."
}

function Set-AppUsers($appid) {
    $users = Import-Csv appusers.csv
    foreach ($user in $users) {
        $appUser = @{
            credentials = @{userName = $user.userName}
            scope = "USER"
        }
        $updAppUser = Set-OktaAppUser $appid $user.id $appUser
    }
}

function Remove-AppUser($appid, $login) {
    $user = Get-OktaUser $login
    $appUser = Set-OktaAppUser $appid $user.id @{scope = "USER"}
    Remove-OktaAppUser $appid $user.id
}

# Events

function Get-Events() {
    $today = Get-Date -Format "yyyy-MM-dd"
    Get-OktaEvents "$($today)T00:00:00.0-08:00"
    # Get-OktaEvents -filter 'published gt "2015-12-21T16:00:00.0-08:00"'
}

# Factors

function Get-MfaUsers {
    $totalUsers = 0
    $mfaUsers = @()
    # 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) {
            $factors = Get-OktaFactors $user.id

            $sms = $factors.where({$_.factorType -eq "sms"})
            $call = $factors.where({$_.factorType -eq "call"})

            $mfaUsers += [PSCustomObject]@{
                id = $user.id
                name = $user.profile.login
                sms = $sms.factorType
                sms_enrolled = $sms.created
                sms_status = $sms.status
                call = $call.factorType
                call_enrolled = $call.created
                call_status = $call.status
            }
        }
        $totalUsers += $users.count
        $params = @{url = $page.nextUrl}
    } while ($page.nextUrl)
    $mfaUsers | Export-Csv mfaUsers.csv -notype
    "$totalUsers users found."
}

function Set-SMSFactor($userid) {
    $factor = @{factorType = "sms"; provider = "OKTA"; profile = @{phoneNumber = "+1-562-555-1212"}}
    $activate = $true # Activate SMS without sending one to the user.
    Set-OktaFactor $userid $factor $activate
}

function Enable-SMSFactor($userid, $factorid, $passCode) {
    # Wait for the user to get an SMS with a passCode, then enable the factor:
    Enable-OktaFactor $userid $factorid @{passCode = $passCode}
}

function Set-RSAFactor($userid) {
    $factor = @{factorType = "token"; provider = "RSA"; profile = @{credentialId = ""}; verify = @{passCode = ""}}
    Set-OktaFactor $userid $factor
}

# Groups

# Read groups from CSV and create them in Okta.
function New-Groups() {
<# Sample groups.csv file with 2 fields. Make sure you include the header line as the first record.
name,description
PowerShell Group,Members of this group are awesome.
#>

    $groups = Import-Csv groups.csv
    $importedGroups = @()
    foreach ($group in $groups) {
        $profile = @{name = $group.name; description = $group.description}
        try {
            $oktaGroup = New-OktaGroup @{profile = $profile}
            $message = "New group"
        } catch {
            Get-Error $_
            try {
                $oktaGroup = Get-OktaGroups $group.name 'type eq "OKTA_GROUP"'
                $message = "Found group"
            } catch {
                Get-Error $_
                $oktaGroup = $null
                $message = "Invalid group"
            }
        }
        $importedGroups += [PSCustomObject]@{id = $oktaGroup.id; name = $group.name; message = $message}
    }
    $importedGroups | Export-Csv importedGroups.csv -notype
    "$($groups.count) groups read." 
}

function Get-PagedGroupMembers($groupId) {
    $totalUsers = 0
    $params = @{id = $groupId; paged = $true}
    do {
        $page = Get-OktaGroupMember @params
        $users = $page.objects
        foreach ($user in $users) {
            Write-Host $user.profile.login
        }
        $totalUsers += $users.count
        $params = @{url = $page.nextUrl; paged = $true}
    } while ($page.nextUrl)
    "$totalUsers users found."
}

function Add-GroupMember() {
    $user = Get-OktaUser "me"
    $group = Get-OktaGroups "PowerShell" 'type eq "OKTA_GROUP"'
    Add-OktaGroupMember $group.id $user.id
}

function Export-Groups() {
    $totalGroups = 0
    $exportedGroups = @()
    # type eq "OKTA_GROUP", "APP_GROUP" (including AD/LDAP), or "BUILT_IN"
    # see https://developer.okta.com/docs/api/resources/groups#group-type
    $filter = 'type eq "APP_GROUP"' 
    $params = @{filter = $filter; paged = $true}
    do {
        $page = Get-OktaGroups @params
        $groups = $page.objects
        foreach ($group in $groups) {
            $exportedGroups += [PSCustomObject]@{id = $group.id; description = $group.profile.description; name = $group.profile.name}
        }
        $totalGroups += $groups.count
        $params = @{url = $page.nextUrl; paged = $true}
    } while ($page.nextUrl)
    $exportedGroups | Export-Csv exportedGroups.csv -notype
    "$($groups.count) groups exported." 
}

# Logs

function Get-Logs() {
    $filePath = "Log.json"
    $flush = 50 # Flush memory every N pages
    $limitRemaining = 10

    $fromTime = Get-Date -Format s
    $fromTime = $fromTime.Substring(0,10) + "T00%3A00%3A00Z"
    $toTime = Get-Date -Format s
    $toTime = $fromTime.Substring(0,10) + "T23%3A59%3A59Z"

    $allLogs = @()
    $pages = 0

    $params = @{since = $fromTime; until = $toTime; sortOrder = "DESCENDING"}
    "[" | Out-File $filePath
    do {
        $page = Get-OktaLogs @params
        $allLogs += $page.objects # these are converted from JSON, but then we convert back to JSON. TODO: optimize.
        $pages++
        if ($pages -eq $flush) {
            Flush-File $allLogs $filePath
            "," | Out-File $filePath -Append
            $allLogs = @()
            $pages = 0
        }
        if ($page.limitRemaining -lt $limitRemaining) {
            do {
                Start-Sleep 1
                $now = [DateTimeOffset]::Now.ToUnixTimeSeconds()
            } until ($now -gt $page.limitReset)
        }
        $params = @{url = $page.nextUrl}
    } while ($page.nextUrl)

    Flush-File $allLogs $filePath

    "]" | Out-File $filePath -Append
}

function Flush-File($allLogs, $filePath) {
    $s = $allLogs | ConvertTo-Json -Compress -Depth 100 # max depth is 100
    $s = $s.substring(1, $s.length - 2) # remove first "[" and last "]"
    $s | Out-File $filePath -Append
}

# Users

# Read users from CSV, create them in Okta, and add to a group. See also next function.
function Import-Users() {
<# Sample users.csv file with 5 fields. Make sure you include the header line as the first record.
login,email,firstName,lastName,groupId
testa1@okta.com,testa1@okta.com,Test,A1,00g5gtwaaeOe7smEF0h7
testa2@okta.com,testa2@okta.com,Test,A2,00g5gtwaaeOe7smEF0h7
#>

    $users = Import-Csv users.csv
    $importedUsers = @()
    foreach ($user in $users) {
        $profile = @{login = $user.login; email = $user.email; firstName = $user.firstName; lastName = $user.lastName}
        $message = ""
        try {
            $oktaUser = New-OktaUser @{profile = $profile} $false
        } catch {
            try {
                $oktaUser = Get-OktaUser $user.login
            } catch {
                $oktaUser = $null
                $message = "Invalid user."
            }
        }
        if ($oktaUser) {
            try {
                Add-OktaGroupMember $user.groupId $oktaUser.id
            } catch {
                $message = "Invalid group."
            }
        }
        $importedUsers += [PSCustomObject]@{id = $oktaUser.id; login = $user.login; message = $message}
    }
    $importedUsers | Export-Csv importedUsers.csv -NoTypeInformation
    "$($users.count) users read."
}

# Read users from CSV, create them in Okta, and add to multiple groups. See also previous function.
function Import-UsersAndGroups() {
<# Sample CSV file with 5 fields. Make sure you include the header line as the first record.
login,email,firstName,lastName,groupIds
testa1@okta.com,testa1@okta.com,Test,A1,"00g5gtwaaeOe7smEF0h7;00g5gtwaaeOe7smFF0h7"
testa2@okta.com,testa2@okta.com,Test,A2,"00g5gtwaaeOe7smEF0h7;00g5gtwaaeOe7smFF0h7"
#>

    $users = Import-Csv usersAndGroups.csv
    foreach ($user in $users) {
        $profile = @{login = $user.login; email = $user.email; firstName = $user.firstName; lastName = $user.lastName}
        $groupIds = $user.groupIds -split ";"
        $oktaUser = New-OktaUser @{profile = $profile; groupIds = $groupIds}
    }
}

# ~ 1000 users / 6 min in oktapreview.com
function New-Users($numUsers) {
    $now = Get-Date -Format "yyyyMMddHHmmss"
    for ($i = 1; $i -le $numUsers; $i++) {
        $profile = @{login="a$now$i@okta.com"; email="testuser$i@okta.com"; firstName="test"; lastName="ZExp$i"}
        try {
            $user = New-OktaUser @{profile = $profile; credentials = @{password = @{value = "Password123"}}} $false
            Write-Host $i
        } catch {
            Get-Error $_
        }
    }
}

function Get-MultipleUsers() {
    $ids = "me#jane.doe".split("#")
    foreach ($id in $ids) {
        $user = Get-OktaUser $id
    }
}

function Get-User() {
    try {
        $user = Get-OktaUser "me"
        $user
    } catch {
        Get-Error $_
    }
}

function Get-PagedUsers() {
    $totalUsers = 0
    $params = @{limit = 200}
    do {
        $page = Get-OktaUsers @params
        $users = $page.objects
        foreach ($user in $users) {
            Write-Host $user.profile.login $user.credentials.provider.type
        }
        $totalUsers += $users.count
        $params = @{url = $page.nextUrl}
    } while ($page.nextUrl)
    "$totalUsers users found."
}

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."
}

function Export-UsersAndGroups() {
    $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) {
            $userGroups = Get-OktaUserGroups $user.id
            $groups = @()
            foreach ($userGroup in $userGroups) {
                if ($userGroup.type -eq "OKTA_GROUP") {
                    $groups += $userGroup.profile.name
                }
            }
            $exportedUsers += [PSCustomObject]@{id = $user.id; login = $user.profile.login; groups = $groups -join ";"}
        }
        $totalUsers += $users.count
        $params = @{url = $page.nextUrl}
    } while ($page.nextUrl)
    $exportedUsers | Export-Csv exportedUsersGroups.csv -notype
    "$totalUsers users exported."
}

function Rename-Users() {
    $page = Get-OktaUsers -filter 'status eq "DEPROVISIONED"'
    $users = $page.objects
    # $oktaCredUsers = $users | where {$_.credentials.provider.type -eq "OKTA"}
    foreach ($user in $users) {
        if ($user.credentials.provider.type -eq "OKTA") {
            $url = Enable-OktaUser $user.id $false
            $updatedUser = Set-OktaUser $user.id @{profile = @{email = "test@gsroka.local"}}
            Disable-OktaUser $user.id
        }
    }
    "$($users.count) users found."
}

function Remove-DeprovisionedUsers() {
    $totalUsers = 0
    $params = @{filter = 'status eq "DEPROVISIONED"'}
    do {
        $page = Get-OktaUsers @params
        $users = $page.objects
        foreach ($user in $users) {
            Write-Host $user.profile.login $user.credentials.provider.type
            Remove-OktaUser $user.id
        }
        $totalUsers += $users.count
        $params = @{url = $page.nextUrl}
    } while ($page.nextUrl)
    "$totalUsers users found."
}

function Remove-UsersBasedOnGroupMembership($groupId) {

# PERMANENTLY DELETE Okta Users. This won't just remove them from a group.

    $totalUsers = 0
    $params = @{id = $groupId; paged = $true}
    do {
        $page = Get-OktaGroupMember @params
        $users = $page.objects
        foreach ($user in $users) {
            Write-Host $user.profile.login
            Remove-OktaUser $user.id # First call sets user to DEPROVISIONED.
            Remove-OktaUser $user.id # Second call deletes user permanently.
        }
        $totalUsers += $users.count
        $params = @{url = $page.nextUrl; paged = $true}
    } while ($page.nextUrl)
    "$totalUsers users deleted."
}

# Zones

function New-Zone() {
    $zone = @{
        type = "IP"
        name = "test"
        gateways = @(
            @{
                type = "RANGE"
                value = "1.2.3.4"
            },
            @{
                type = "CIDR"
                value = "5.6.7.8/24"
            }
        )
    }
    New-OktaZone $zone
}

# Rate limits

# https://developer.okta.com/docs/reference/rate-limits
function Get-RateLimits() {
    $urlLimit = 1200 # this varies by URL
    $remaining = $urlLimit
    for ($i = 1; $i -le 5000; $i++) {
        $now = [DateTimeOffset]::Now.ToUnixTimeSeconds()
        if ($remaining -gt 20) {
            try {
                $page = Get-OktaUsers -filter 'profile.login eq "gabriel.sroka@lokta.com"'
                $limit = $page.limitLimit
                $remaining = $page.limitRemaining
                $reset = $page.limitReset
                Write-Host "now: " + $now + " remaining: " + $remaining + " reset: " + $reset
            } catch {
                Write-Host "Error ! (need to redo last call)."
                $remaining = 0
            }
        } else {
            Write-Host "waiting, now: " + $now + " reset: " + $reset
            if ($now -gt $reset) {
                Write-Host "reset"
                $remaining = $urlLimit
            }
            Start-Sleep -second 1
        }
    }
}


<#PSScriptInfo
.VERSION 1.1.13
.GUID 33ca8742-b9bf-4824-9d86-605a8d627cb4
.AUTHOR Gabriel Sroka
.DESCRIPTION Call Okta API.
.PROJECTURI https://github.com/gabrielsroka/OktaAPI.psm1
#>