This repository has been archived by the owner on Feb 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathAdobeUMInterface.psm1
1274 lines (1079 loc) · 45.7 KB
/
AdobeUMInterface.psm1
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#region Helper functions (General use functions)
#These functions are general use functions to make life easier. Primarily, they make converting to/from Java objects easier, and they assist in setting up the initial connection with Adobe
<#
.SYNOPSIS
Creates a new self-signed certificate for use with Adobe.
.PARAMETER DNSName
Name to append to cert. Defaults to "ADOBEAUTH.<yourdomain>"
.PARAMETER ExpiryYears
How long before the certificate expires in years. Defaults to 6
.PARAMETER Quiet
Suppresses message on where to find cert
.OUTPUTS
New certificate in the current user's certificate store
.NOTES
This is required to sign a JWT that will authenticate the service account.
After a cert is created, export it without the private key and upload it to your service account's information page at https://console.adobe.io/
Export the private key as a pfx file and store it somewhere. Ensure you know the password as it is required.
.EXAMPLE
New-Cert
#>
function New-Cert
{
Param
(
[string]$DNSName="ADOBEAUTH."+$env:USERDNSDOMAIN,
[int]$ExpiryYears=6,
[switch]$Quiet
)
$CmdLetParam = (Get-Help -Name New-SelfSignedCertificate -Full).parameters.parameter | Where-Object {$_.name -eq "Provider"}
if ($CmdLetParam) {
$Cert=New-SelfSignedCertificate -CertStoreLocation cert:\currentuser\my -DnsName $DNSName -KeyFriendlyName $DNSName -NotAfter ([DateTime]::Now).AddYears($ExpiryYears) -HashAlgorithm "SHA512" -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider"
if (-not $Quiet) {
Write-Host ("Your certificate has been created. You may find it in your certificate store. (Run MMC.exe as "+$env:USERNAME+"@"+$env:USERDNSDOMAIN+")")
Write-Host "Add the certificate snap-in and you should find the new cert at 'Certificates - Current User\Personal\Certificates\$DNSName'"
Write-Host "Right-Click the cert to export it with and without its private key"
}
} else {
Write-Error "Your version of PowerShell/Windows does not support advanced features for the New-SelfSignedCertificate cmdlet. Please manually generate a certificate preferably using the `"Microsoft Enhanced RSA and AES Cryptographic Provider`" CSP."
}
}
<#
.SYNOPSIS
Load a certificate with a private key from file
.PARAMETER Password
Password to open PFX
.PARAMETER CertPath
Path to PFX File
.NOTES
If you hard-code the password in a script utilizing this function, you should ensure the script is itself, somewhere secure
.EXAMPLE
Import-PFXCert -Password "ASDF" -CertPath "C:\Cert.pfx"
#>
function Import-PFXCert
{
[Obsolete("This cmdlet is obsolete. Please use Import-AdobeUMCert instead.")]
Param
(
[string]$Password,
[ValidateScript({Test-Path -Path $_})]
[Parameter(Mandatory=$true)][string]$CertPath
)
$Collection = [System.Security.Cryptography.X509Certificates.X509Certificate2Collection]::new()
$Collection.Import($CertPath, $Password, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet)
return $Collection[0]
}
<#
.SYNOPSIS
Load a certificate with a private key from either a file or from a certificate store
.PARAMETER Password
Password to open PFX
.PARAMETER CertPath
Path to PFX File
.PARAMETER CertThumbprint
Thumbprint of the cert to load
.PARAMETER CertStore
Which store to load cert from (LocalMachine or CurrentUser)
.NOTES
If you hard-code the password in a script utilizing this function, you should ensure the script is itself, somewhere secure.
The account running this function may need additional permissions to load private key from LocalMachine store.
.EXAMPLE
Import-AdobeUMCert -Password "ASDF" -CertPath "C:\Cert.pfx"
.EXAMPLE
Import-AdobeUMCert -CertThumbprint "00000000000000000000000000000000" -CertStore "LocalMachine"
#>
function Import-AdobeUMCert
{
Param
(
[Parameter(Mandatory=$true,ParameterSetName='FromFile')][string]$Password,
[ValidateScript({Test-Path -Path $_})]
[Parameter(Mandatory=$true,ParameterSetName='FromFile')][string]$CertPath,
[Parameter(Mandatory=$true,ParameterSetName='FromStore')][string]$CertThumbprint,
[Parameter(Mandatory=$true,ParameterSetName='FromStore')][ValidateSet('CurrentUser','LocalMachine')]$CertStore
)
$Collection = @()
if ($PSCmdlet.ParameterSetName -eq "FromStore") {
#Convert cert store to the correct enum value
if ($CertStore -eq "CurrentUser") {
$CertStore = [System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser
} elseif ($CertStore -eq "LocalMachine") {
$CertStore = [System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine
}
#Open the certificate store
$Store = New-Object -TypeName System.Security.Cryptography.X509Certificates.x509Store -ArgumentList @($CertStore)
$Store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly)
#Cleanup Thumbprint (Remove spaces, make uppercase, and remove hidden null characters from copy-paste)
$CertThumbprint = $CertThumbprint.ToUpper() -replace "[^\w\d]",""
#Now search for certificate by thumbprint
$Collection = $Store.Certificates.Find([System.Security.Cryptography.X509Certificates.X509FindType]::FindByThumbprint, $CertThumbprint, $false)
$Store.Dispose() #Make sure we cleanup after ourselves
}
elseif ($PSCmdlet.ParameterSetName -eq "FromFile")
{
#Load cert in by file
$Collection = [System.Security.Cryptography.X509Certificates.X509Certificate2Collection]::new()
$Collection.Import($CertPath, $Password, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet)
}
if ($Collection.Length -lt 1) {
Write-Error "Did not find any certificates in specified store"
return $null
}
return $Collection[0]
}
<#
.SYNOPSIS
Converts a byte[], to a Base64URL encoded string
.PARAMETER Item
A byte[]
.EXAMPLE
ConvertTo-Base64URL -Item "VGhpcyBpcyBhIHRlc3Q="
#>
function ConvertTo-Base64URL
{
Param([Parameter(Mandatory=$true)]$Item)
return [Convert]::ToBase64String($Item).Split("=")[0].Replace('+', '-').Replace('/', '_')
}
<#
.SYNOPSIS
Converts a Base64Url string, to a decoded ASCII string
.PARAMETER Item
A base64url string
.EXAMPLE
ConvertFrom-Base64URL -Item "VGhpcyBpcyBhIHRlc3Q"
#>
function ConvertFrom-Base64URL
{
Param([Parameter(Mandatory=$true)][string]$String)
return [System.Text.ASCIIEncoding]::ASCII.GetString([convert]::FromBase64String((ConvertFrom-Base64URLToBase64 -String $String)))
}
<#
.SYNOPSIS
Converts a Base64Url string, to a .Net base64 string
.PARAMETER Item
A base64url string
.EXAMPLE
ConvertFrom-Base64URLToBase64 -Item "VGhpcyBpcyBhIHRlc3Q"
#>
function ConvertFrom-Base64URLToBase64
{
Param([Parameter(Mandatory=$true)][string]$String)
$String = $String.Replace('-', '+').Replace('_', '/')
while ((($String.Length)*6)%8-ne 0)
{
$String = $String+"="
}
return $String
}
<#
.SYNOPSIS
Converts the [datetime] object passed into a java compliant numerical representation. (milliseconds since 1/1/1970)
.PARAMETER DateTimeObject
A DateTime to be converted
.EXAMPLE
ConvertTo-JavaTime -DateTimeObject ([DateTime]::Now)
#>
function ConvertTo-JavaTime
{
Param([Parameter(Mandatory=$true)][DateTime]$DateTimeObject)
#Take DateTime, convert to file time (100 nano second ticks since 1/1/1607). Subtract 1/1/1970 from that using the same 100nanoticks. Then multiply to convert from nanoticks to milliseconds since 1/1/1970.
return [int64](($DateTimeObject.ToFileTimeUtc()-[DateTime]::Parse("01/01/1970").ToFileTimeUtc())*0.0001)
}
<#
.SYNOPSIS
Converts the java compliant numerical representation of time to a .net [datetime] object.
.PARAMETER JavaTime
A JavaTime to be converted
.EXAMPLE
ConvertFrom-JavaTime -JavaTime 1500000000000
#>
function ConvertFrom-JavaTime
{
Param([Parameter(Mandatory=$true)][int64]$JavaTime)
#Take the javatime, multiply it by 10000 to convert from millisecond ticks to 100 nanosecond ticks. Then add the 100 nano second tickets since 1970 to that number. This gives us the current file time.
#Then convert file time to [datetime] object
return [DateTime]::FromFileTimeUtc($JavaTime*10000+[DateTime]::Parse("01/01/1970").ToFileTimeUtc())
}
<#
.SYNOPSIS
Unpacks a JWT object into it's header, and body components. (Human readable format)
.PARAMETER JWTObject
JWT To unpack. In format of {Base64Header}.{Base64Body}.{Base64Signature}
.PARAMETER SigningCert
A certificate with the necesary public key to verify signature block. Can be null, will not validate signature.
.NOTES
See https://adobe-apiplatform.github.io/umapi-documentation/en/RefOverview.html
This should be posted to https://usermanagement.adobe.io/v2/usermanagement/action/{myOrgID}
.EXAMPLE
Expand-JWTInformation -JWTObject "xxxx.xxxx.xxx"
#>
function Expand-JWTInformation
{
Param
(
[ValidateScript({$_.Split(".").Length -eq 3})]
[Parameter(Mandatory=$true)][string]$JWTObject,
$SigningCert
)
$JWTParts = $JWTObject.Split(".")
$Header =(ConvertFrom-Json -InputObject (ConvertFrom-Base64URL -String $JWTParts[0]));
$RawData = [System.Text.ASCIIEncoding]::ASCII.GetBytes($JWTParts[0]+"."+$JWTParts[1])
$Signature = [System.Convert]::FromBase64String((ConvertFrom-Base64URLToBase64 -String $JWTParts[2]))
$Valid= $null
if ($SigningCert -and $Header.alg.StartsWith("RS"))
{
$HAN=$null
if ($Header.alg.EndsWith("256"))
{
$HAN = [System.Security.Cryptography.HashAlgorithmName]::SHA256
}
elseif ($Header.alg.EndsWith("512"))
{
$Han = [System.Security.Cryptography.HashAlgorithmName]::SHA512
}
elseif ($Header.alg.EndsWith("384"))
{
$Han = [System.Security.Cryptography.HashAlgorithmName]::SHA384
}
if ($HAN)
{
$Valid = $SigningCert.PublicKey.Key.VerifyData($RawData, $Signature, $Han, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1)
}
else
{
Write-Warning "Hash algorithm not supported, the signature of the JWT was not verified."
}
}
else
{
Write-Warning "Either no certificate was passed to function, or Hash algorithm not supported, either way, the signature of the JWT was not verified."
}
return (New-Object -TypeName PSObject -ArgumentList @{Header=$Header;
Body=(ConvertFrom-Json -InputObject (ConvertFrom-Base64URL -String $JWTParts[1]));
SignatureValid=$Valid})
}
#endregion
#region Connection setup functions
#These functions are directly used in logging into Adobe with JWT.
<#
.SYNOPSIS
Creates an object to contain client information such as service account details.
.PARAMETER APIKey
Your service account's APIkey/ClientID as returned by https://console.adobe.io/
.PARAMETER OrganizationID
Your OrganizationID as returned by https://console.adobe.io/
.PARAMETER ClientSecret
Your service account's ClientSecret as returned by https://console.adobe.io/
.PARAMETER TechnicalAccountID
Your service account's TechnicalAccountID as returned by https://console.adobe.io/
.PARAMETER TechnicalAccountEmail
Your service account's TechnicalAccountEmail as returned by https://console.adobe.io/
.OUTPUTS
ClientInformation object to be passed to further commands
.NOTES
The information required by this function is provided to you by Adobe when you create an integration at https://console.adobe.io/
.EXAMPLE
New-ClientInformation -APIKey "1111111111111222222333" -OrganizationID "22222222222222@AdobeOrg" -ClientSecret "xxxx-xxxx-xxxx-xxxx" -TechnicalAccountID "[email protected]" -TechnicalAccountEmail "[email protected]"
#>
function New-ClientInformation
{
Param
(
[Parameter(Mandatory=$true)][string]$APIKey,
[Parameter(Mandatory=$true)][string]$OrganizationID,
[Parameter(Mandatory=$true)][string]$ClientSecret,
[Parameter(Mandatory=$true)][string]$TechnicalAccountID,
[Parameter(Mandatory=$true)][string]$TechnicalAccountEmail
)
return New-Object -TypeName PSObject -ArgumentList @{
APIKey = $APIKey; # ClientID
ClientID = $APIKey; # Alias, adobe flip flops on what they call this
OrgID = $OrganizationID;
ClientSecret = $ClientSecret;
TechnicalAccountID = $TechnicalAccountID;
TechnicalAccountEmail = $TechnicalAccountEmail;
Token=$null;
}
}
<#
.SYNOPSIS
Adds an adobe auth token to the ClientInformation object passed to it
.PARAMETER ClientInformation
Your ClientInformation object
.PARAMETER SignatureCert
The cert that is attached to the specified account. Must have private key. Check which cert at https://console.adobe.io/
.PARAMETER AuthTokenURI
URI of the Adobe Auth Service. Defaults to https://ims-na1.adobelogin.com/ims/exchange/jwt/
.PARAMETER ExpirationInHours
When the request token should expire in hours. Defaults to 1
.OUTPUTS
Attached auth token to ClientInformation.Token
.NOTES
Create JWT https://www.adobe.io/apis/cloudplatform/console/authentication/createjwt/jwt_nodeJS.html
https://github.com/lambtron/nextbus/blob/master/node_modules/jwt-simple/lib/jwt.js
https://jwt.io/
.EXAMPLE
Get-AdobeAuthToken -ClientInformation $MyClient -SignatureCert $Cert -ExpirationInHours 12
#>
function Get-AdobeAuthToken
{
Param
(
[Parameter(Mandatory=$true)]$ClientInformation,
[ValidateScript({$_.PrivateKey -ne $null})]
[Parameter(Mandatory=$true)]$SignatureCert,
[string]$AuthTokenURI="https://ims-na1.adobelogin.com/ims/exchange/jwt/",
[int]$ExpirationInHours=1
)
$PayLoad = New-Object -TypeName PSObject -Property @{
iss=$ClientInformation.OrgID;
sub=$ClientInformation.TechnicalAccountID;
aud="https://ims-na1.adobelogin.com/c/"+$ClientInformation.APIKey;
"https://ims-na1.adobelogin.com/s/ent_user_sdk"=$true;#MetaScope
exp=(ConvertTo-JavaTime -DateTimeObject ([DateTime]::Now.AddHours($ExpirationInHours)));
}
#Header for the JWT
$Header = ConvertTo-Json -InputObject (New-Object PSObject -Property @{"typ"="JWT";"alg"="RS256"}) -Compress
#Body of the JWT. This is our actual request
$JWT = ConvertTo-Base64URL -Item ([System.Text.ASCIIEncoding]::ASCII.GetBytes((ConvertTo-Json -InputObject $PayLoad -Compress)))
#Join them together. as base64 strings, with a "." between them
$JWT = (ConvertTo-Base64URL -Item ([System.Text.ASCIIEncoding]::ASCII.GetBytes($Header)))+"."+$JWT
#Sign the data
try {
$JWTSig = ConvertTo-Base64URL -Item ($SignatureCert.PrivateKey.SignData([System.Text.ASCIIEncoding]::UTF8.GetBytes($JWT), [System.Security.Cryptography.HashAlgorithmName]::SHA256, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1)) -ErrorAction Stop
} catch [CryptographicException] {
Write-Warning "Could not sign the data. Please ensure your certificate was imported using the 'Microsoft Enhanced RSA and AES Cryptographic Provider' CSP. See https://github.com/zincarla/AdobeUMInterface/issues/10 for more information."
throw $_
} catch {
throw $_
}
#Append the signature. This is now a complete JWT
$JWT = $JWT+"."+$JWTSig
#Now we request the auth token
$Body = "client_id=$($ClientInformation.APIKey)&client_secret=$($ClientInformation.ClientSecret)&jwt_token=$JWT"
$ClientInformation.Token=Invoke-RestMethod -Method Post -Uri $AuthTokenURI -Body $Body -ContentType "application/x-www-form-urlencoded"
}
#endregion
#region Read Functions
#These are functions that can be called to query data from Adobe. These do -not- need to be sent with Send-UserManagementRequest
<#
.SYNOPSIS
Gets all users from the adobe API
.PARAMETER ClientInformation
Your ClientInformation object
.PARAMETER UM_Server
The adobe user management uri. Defaults to "https://usermanagement.adobe.io/v2/usermanagement/"
.PARAMETER Page
You may manually specify a specific page to retrieve from Adobe. Otherwise a value < 0 will return all users
.EXAMPLE
Get-AdobeUsers -ClientInformation $MyClient
#>
function Get-AdobeUsers
{
Param
(
[string]$UM_Server="https://usermanagement.adobe.io/v2/usermanagement/",
[int]$Page=-1,
[ValidateScript({$_.Token -ne $null})]
[Parameter(Mandatory=$true)]$ClientInformation
)
#https://adobe-apiplatform.github.io/umapi-documentation/en/api/user.html
#Store the results here
$Results = @()
#URI of the query endpoint
$URIPrefix = $UM_Server+"users/$($ClientInformation.OrgID)/"
$LoopToEnd = $true;
if ($Page -lt 0) {
$Page =0
} else {
$LoopToEnd = $false;
}
#Request headers
$Headers = @{Accept="application/json";
"Content-Type"="application/json";
"x-api-key"=$ClientInformation.APIKey;
Authorization="Bearer $($ClientInformation.Token.access_token)"}
#Query, looping through each page, until we have all users.
while($true)
{
try {
$QueryResponse = Invoke-RestMethod -Method Get -Uri ($URIPrefix+$Page.ToString()) -Header $Headers
} catch {
if ($_.Exception.Response.StatusCode.value__ -eq '429') {
#https://adobe-apiplatform.github.io/umapi-documentation/en/api/ActionsRef.html#actionThrottle
Write-Warning "Adobe is throttling our user query. This cmdlet will now sleep 30 seconds and continue."
Start-Sleep -Seconds 30
$Paused = $true
}
}
if ($Paused -eq $true) {
#reset paused flag so loop can try getting page again
$Paused = $false
}
else {
#Currently not required, but other queries will just keep dumping the same users as you loop though pages
if ($Results -ne $null -and (@()+$Results.email).Contains($QueryResponse[0].email))
{
break;
}
$Results += $QueryResponse.users
$Page++;
#Different API endpoints have different ways of telling you if you are done.
if ($QueryResponse.lastPage -eq $true -or $QueryResponse -eq $null -or $QueryResponse.Length -eq 0 -or -not $LoopToEnd)
{
break;
}
}
}
return $Results
}
<#
.SYNOPSIS
Gets a single user from the adobe API
.PARAMETER ClientInformation
Your ClientInformation object
.PARAMETER UM_Server
The adobe user management uri. Defaults to "https://usermanagement.adobe.io/v2/usermanagement/"
.PARAMETER UserID
ID (Usually email) of the user to retrieve
.NOTES
https://adobe-apiplatform.github.io/umapi-documentation/en/api/getUser.html
.EXAMPLE
Get-AdobeUser -ClientInformation $MyClient -UserID "[email protected]"
#>
function Get-AdobeUser
{
Param
(
[string]$UM_Server="https://usermanagement.adobe.io/v2/usermanagement/",
[Parameter(Mandatory=$true)][string]$UserID,
[ValidateScript({$_.Token -ne $null})]
[Parameter(Mandatory=$true)]$ClientInformation
)
#URI of the query endpoint
$URIPrefix = "$($UM_Server)organizations/$($ClientInformation.OrgID)/users/$UserID"
#Request headers
$Headers = @{Accept="application/json";
"Content-Type"="application/json";
"x-api-key"=$ClientInformation.APIKey;
Authorization="Bearer $($ClientInformation.Token.access_token)"}
#Query
while($true) {
try {
$QueryResponse = Invoke-RestMethod -Method Get -Uri $URIPrefix -Header $Headers
if ($QueryResponse.result.StartsWith("error") ) {
Write-Error $QueryResponse.result;
return $null
}
return $QueryResponse.user
} catch {
if ($_.Exception.Response.StatusCode -eq 429) {
#https://adobe-apiplatform.github.io/umapi-documentation/en/api/getUsersWithPage.html#getUsersWithPageThrottle
Write-Warning "Adobe is throttling our user query. This cmdlet will now sleep the requested $($_.Exception.Response.Headers["Retry-After"]) seconds before retrying..."
Start-Sleep -Seconds $_.Exception.Response.Headers["Retry-After"]
Write-Warning "Continuing with query."
} elseif ($_.Exception.Response.StatusCode -eq 404) {
# User not found
return $null
} else {
Write-Error $_.Exception;
return $null
}
}
}
}
<#
.SYNOPSIS
Grab a list of all groups, or if provided an ID, returns the group related to the ID
.PARAMETER ClientInformation
Your ClientInformation object
.PARAMETER UM_Server
The adobe user management uri. Defaults to "https://usermanagement.adobe.io/v2/usermanagement/"
.PARAMETER GroupID
If you wish to query for a single group instead, put the group ID here. [DEPRECATED!]
.EXAMPLE
Get-AdobeGroups -ClientInformation $MyClient
.EXAMPLE
Get-AdobeGroups -ClientInformation $MyClient -GroupID "222242"
#>
function Get-AdobeGroups
{
Param
(
[string]$UM_Server="https://usermanagement.adobe.io/v2/usermanagement/",
$GroupID=$null,
[ValidateScript({$_.Token -ne $null})]
[Parameter(Mandatory=$true)]$ClientInformation
)
$Results = @()
if ($GroupID -eq $null)
{
$URIPrefix = $UM_SERVER+"groups/$($ClientInformation.OrgID)/"
}
else
{
$URIPrefix = "$UM_SERVER$($ClientInformation.OrgID)/user-groups/$GroupID"
#https://adobe-apiplatform.github.io/umapi-documentation/en/api/group.html
Write-Warning "This function is deprecated for use in getting a single group. There does not appear to be a replacement for this in the new API."
}
$Page =0
#Request headers
$Headers = @{Accept="application/json";
"Content-Type"="application/json";
"x-api-key"=$ClientInformation.APIKey;
Authorization="Bearer $($ClientInformation.Token.access_token)"}
if ($GroupID -eq $null)
{
while($true)
{
$QueryResponse = Invoke-RestMethod -Method Get -Uri ($URIPrefix+$Page.ToString()) -Header $Headers
if ($QueryResponse.error_code -ne $null -and $QueryResponse.error_code.ToString().StartsWith("429")) {
#https://adobe-apiplatform.github.io/umapi-documentation/en/api/getUsersWithPage.html#getUsersWithPageThrottle
#I never got blocked testing this, not sure if this is needed, but just in case it does
Write-Warning "Adobe is throttling our query. This cmdlet will now sleep 1 minute and continue."
Start-Sleep -Seconds 60
}
else {
$Results += $QueryResponse.groups
$Page++;
if ($QueryResponse.lastPage -eq $true -or $QueryResponse -eq $null -or $QueryResponse.Length -eq 0)
{
break
}
}
}
}
else
{
$Results = Invoke-RestMethod -Method Get -Uri $URIPrefix -Header $Headers
}
return $Results
}
<#
.SYNOPSIS
Grab all members of the specified group
.PARAMETER ClientInformation
Your ClientInformation object
.PARAMETER UM_Server
The adobe user management uri. Defaults to "https://usermanagement.adobe.io/v2/usermanagement/"
.PARAMETER GroupName
The Name of the group to query
.EXAMPLE
Get-AdobeGroupMembers -ClientInformation $MyClient -GroupName "All Apps Users"
#>
function Get-AdobeGroupMembers
{
Param
(
[string]$UM_Server="https://usermanagement.adobe.io/v2/usermanagement/",
[ValidateScript({$_.Token -ne $null})]
[Parameter(Mandatory=$true)]$ClientInformation,
[Parameter(Mandatory=$true)][string]$GroupName
)
$Results = @()
$URIPrefix = $UM_SERVER+"users/$($ClientInformation.OrgID)/{PAGE}/$GroupName" #Yes page before groupname...
$Page =0
#Request headers
$Headers = @{Accept="application/json";
"Content-Type"="application/json";
"x-api-key"=$ClientInformation.APIKey;
Authorization="Bearer $($ClientInformation.Token.access_token)"}
while($true)
{
$QueryResponse = Invoke-RestMethod -Method Get -Uri ($URIPrefix.Replace("{PAGE}", $Page.ToString())) -Header $Headers
if ($QueryResponse.error_code -ne $null -and $QueryResponse.error_code.ToString().StartsWith("429")) {
#https://adobe-apiplatform.github.io/umapi-documentation/en/api/getUsersWithPage.html#getUsersWithPageThrottle
#I never got blocked testing this, not sure if this is needed, but just in case it does
Write-Warning "Adobe is throttling our query. This cmdlet will now sleep 1 minute and continue."
Start-Sleep -Seconds 60
}
else
{
$Results += $QueryResponse.users
$Page++;
if ($QueryResponse.lastPage -eq $true -or $QueryResponse -eq $null -or $QueryResponse.users.Length -eq 0)
{
break
}
}
}
return $Results
}
<#
.SYNOPSIS
Grab all admins of the specified group
.PARAMETER ClientInformation
Your ClientInformation object
.PARAMETER UM_Server
The adobe user management uri. Defaults to "https://usermanagement.adobe.io/v2/usermanagement/"
.PARAMETER GroupName
The Name of the group to query
.EXAMPLE
Get-AdobeGroupAdmins -ClientInformation $MyClient -GroupName "All Apps Users"
#>
function Get-AdobeGroupAdmins
{
Param
(
$UM_Server="https://usermanagement.adobe.io/v2/usermanagement/",
[ValidateScript({$_.Token -ne $null})]
[Parameter(Mandatory=$true)]$ClientInformation,
[Parameter(Mandatory=$true)][string]$GroupName
)
#See https://www.adobe.io/apis/cloudplatform/usermanagement/docs/samples/samplequery.html
$Results = @()
$URIPrefix = $UM_SERVER+"users/$($ClientInformation.OrgID)/{PAGE}/_admin_$GroupName"
$Page =0
#Request headers
$Headers = @{Accept="application/json";
"Content-Type"="application/json";
"x-api-key"=$ClientInformation.APIKey;
Authorization="Bearer $($ClientInformation.Token.access_token)"}
while($true)
{
$QueryResponse = Invoke-RestMethod -Method Get -Uri ($URIPrefix.Replace("{PAGE}", $Page.ToString())) -Header $Headers
if ($QueryResponse.error_code -ne $null -and $QueryResponse.error_code.ToString().StartsWith("429")) {
#https://adobe-apiplatform.github.io/umapi-documentation/en/api/getUsersWithPage.html#getUsersWithPageThrottle
#I never got blocked testing this, not sure if this is needed, but just in case it does
Write-Warning "Adobe is throttling our query. This cmdlet will now sleep 1 minute and continue."
Start-Sleep -Seconds 60
}
else
{
$Results += $QueryResponse.users
$Page++;
if ($QueryResponse.lastPage -eq $true -or $QueryResponse -eq $null -or $QueryResponse.users.Length -eq 0)
{
break
}
}
}
return $Results
}
#endregion
#region Request Functions
#These functions create entire request objects. This allows you to create a user, without having to build the entire JSON object from scratch
<#
.SYNOPSIS
Creates a "CreateUserRequest" object. This object can then be converted to JSON and sent to create a new user
.PARAMETER FirstName
User's First name
.PARAMETER LastName
User's Last Name
.PARAMETER Email
User's Email and ID
.PARAMETER Country
Defaults to US. This cannot be changed later. (Per adobe documentation)
.PARAMETER IDType
Specify the type of account to create. Valid values are enterprise,adobe,federated. Defaults to enterprise.
.PARAMETER Domain
Only required if using federated access. If username is email, ommit this. Otherwise include for federated users.
.PARAMETER UserID
Manually specify the user identity. Defaults to Email
.PARAMETER AdditionalActions
An array of additional actions to add to the request. (Like add to group)
.PARAMETER OptionOnDuplicate
Option to perform when a user already exists. Either ignoreIfAlreadyExists or updateIfAlreadyExists
.NOTES
See https://adobe-apiplatform.github.io/umapi-documentation/en/RefOverview.html
This should be posted to https://usermanagement.adobe.io/v2/usermanagement/action/{myOrgID}
.EXAMPLE
New-CreateUserRequest -FirstName "John" -LastName "Doe" -Email "[email protected]" -IDType enterprise
.EXAMPLE
New-CreateUserRequest -FirstName "John" -LastName "Doe" -UserID "John.Doe" -Email "[email protected]" -IDType federated
#>
function New-CreateUserRequest
{
Param
(
[Parameter(Mandatory=$true)][string]$FirstName,
[Parameter(Mandatory=$true)][string]$LastName,
[Parameter(Mandatory=$true)][string]$Email,
[string]$UserID=$Email,
[ValidateSet("enterprise","federated", "adobe")]
$IDType="enterprise",
$Domain,
[string]$Country="US",
$AdditionalActions=@(),
[ValidateSet("ignoreIfAlreadyExists","updateIfAlreadyExists")]
$OptionOnDuplicate="ignoreIfAlreadyExists"
)
#Properties required for all account types
$IDParameters = New-Object -TypeName PSObject -Property @{email=$Email;country=$Country;firstname=$FirstName;lastname=$LastName}
#Add option if it exists
if ($OptionOnDuplicate -ne $null) {
$IDParameters | Add-Member -MemberType NoteProperty -Name "option" -Value $OptionOnDuplicate
}
$CreateAction = $null;
if ($IDType -eq "enterprise") {
$CreateAction = New-Object -TypeName PSObject -Property @{createEnterpriseID=$IDParameters}
}
elseif ($IDType -eq "federated") {
$CreateAction = New-Object -TypeName PSObject -Property @{createFederatedID=$IDParameters}
}
elseif ($IDType -eq "adobe") {
$CreateAction = New-Object -TypeName PSObject -Property @{addAdobeID=$IDParameters}
}
#Add any additional actions
$AdditionalActions = @()+ $CreateAction + $AdditionalActions
#Build and return the new request
$Request = New-Object -TypeName PSObject -Property @{user=$UserID;do=@()+$AdditionalActions}
#Adobe and federated require another field
if ($Domain -ne $null) {
$Request | Add-Member -MemberType NoteProperty -Name "domain" -Value $Domain
}
if ($IDType -eq "adobe") {
$Request | Add-Member -MemberType NoteProperty -Name "useAdobeID" -Value "true"
}
return $Request;
}
<#
.SYNOPSIS
Creates a "RemoveUserRequest" object. This object can then be converted to JSON and sent to remove a user from adobe
.PARAMETER UserName
User's ID, usually e-mail
.PARAMETER Domain
User's domain, only required for some types of federated id
.PARAMETER AdditionalActions
An array of additional actions to add to the request. (Like add to group)
.NOTES
See https://adobe-apiplatform.github.io/umapi-documentation/en/RefOverview.html
This should be posted to https://usermanagement.adobe.io/v2/usermanagement/action/{myOrgID}
.EXAMPLE
New-RemoveUserRequest -UserName "[email protected]"
#>
function New-RemoveUserRequest
{
Param
(
[Parameter(Mandatory=$true)][string]$UserName,
[string]$Domain,
$AdditionalActions=@()
)
$RemoveAction = New-Object -TypeName PSObject -Property @{removeFromOrg=(New-Object -TypeName PSObject)}
$AdditionalActions = @() + $RemoveAction + $AdditionalActions
#Build and return request
$Request = New-Object -TypeName PSObject -Property @{user=$UserName;do=@()+$AdditionalActions}
if ($Domain) {
$Request | Add-Member -MemberType NoteProperty -Name "domain" -Value $Domain
}
return $Request
}
<#
.SYNOPSIS
Creates a request to remove a user from an Adobe group. This will need to be posted after being converted to a JSON
.PARAMETER UserName
User's ID, usually e-mail
.PARAMETER Groups
Name of the group to remove the user from
.NOTES
See https://adobe-apiplatform.github.io/umapi-documentation/en/RefOverview.html
This should be posted to https://usermanagement.adobe.io/v2/usermanagement/action/{myOrgID}
.EXAMPLE
New-RemoveUserFromGroupRequest -UserName "[email protected]" -Groups "My User Group"
#>
function New-RemoveUserFromGroupRequest
{
[Alias("New-RemoveFromGroupRequest")]
Param
(
[Alias("User")][Parameter(Mandatory=$true)][string]$UserName,
[string]$Domain,
[Alias("GroupName")][Parameter(Mandatory=$true)]$Groups
)
$RemoveMemberAction = New-GroupUserRemoveAction -Groups $Groups
#Build and return request
$Request = New-Object -TypeName PSObject -Property @{user=$UserName;do=@()+$RemoveMemberAction}
if ($Domain) {
$Request | Add-Member -MemberType NoteProperty -Name "domain" -Value $Domain
}
return $Request
}
<#
.SYNOPSIS
Creates a "Add user to group" request. This will need to be json'd and sent to adobe
.PARAMETER Groups
An array of groups that something should be added to
.NOTES
See https://adobe-apiplatform.github.io/umapi-documentation/en/RefOverview.html
This should be posted to https://usermanagement.adobe.io/v2/usermanagement/action/{myOrgID}
.EXAMPLE
New-AddToGroupRequest -Groups "My User Group" -User "[email protected]"
#>
function New-AddToGroupRequest
{
[Alias("New-AddUserToGroupRequest")]
Param
(
[Parameter(Mandatory=$true)][string]$User,
[Parameter(Mandatory=$true)]$Groups
)
$GroupAddAction = New-GroupUserAddAction -Groups $Groups
return (New-Object -TypeName PSObject -Property @{user=$User;do=@()+$GroupAddAction})
}
<#
.SYNOPSIS
Creates an array of requests that effectively mirrors an Adobe group to an AD group
.DESCRIPTION
Creates an array of requests that, when considered together, ensures an Adobe group will mirror an AD group
.PARAMETER ADGroupName
Active Directory Group Identifier (Name or DN). The source group to mirror to adobe
.PARAMETER AdobeGroupName
Adobe group Name
.PARAMETER RecurseADGroupMembers
If specified, will pull all users in all groups in and under the specified ADGroup
.PARAMETER DeleteRemovedMembers
Removes users from the Adobe Console if they have been removed from the group
.PARAMETER CreateAsFederated
If a new user needs to be created in Adobe, this switch creates them with a federatedID instead of an EnterpriseID
.PARAMETER Country
Country for new users, defaults to US. This cannot be changed later. (Per adobe documentation)
.PARAMETER ClientInformation
Service account information including token
.EXAMPLE
New-SyncADGroupRequest -ADGroupName "SG-My-Adobe-Users" -AdobeGroupName "All Apps Users" -ClientInformation $MyClientInfo
.NOTES
If you accidently remove an admin account using DeleteRemovedMembers, you can still recover using the API.
#>
Function New-SyncADGroupRequest {