-
Notifications
You must be signed in to change notification settings - Fork 12
/
AzureADB2C-Scripts.psm1
3600 lines (3064 loc) · 143 KB
/
AzureADB2C-Scripts.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
<#
.SYNOPSIS
Downloads the Azure AD B2C Starer Pack
.DESCRIPTION
Downloads the Azure AD B2C Custom Policy Starter Pack from https://github.com/Azure-Samples/active-directory-b2c-custom-policy-starterpack
.PARAMETER PolicyPath
Path to store the downloades files. Current Directory is default
.PARAMETER PolicyType
The type of policies to download. SocialAndLocalAccounts is default
.PARAMETER PolicyFile
Filename if only downloading a single file.
.EXAMPLE
Get-AzureADB2CStarterPack -PolicyType "SocialAndLocalAccountsWithMfa"
#>
function Get-AzureADB2CStarterPack(
[Parameter(Mandatory=$false)][Alias('p')][string]$PolicyPath = "",
[Parameter(Mandatory=$false)][Alias('b')][string]$PolicyType = "SocialAndLocalAccounts",
[Parameter(Mandatory=$false)][Alias('f')][string]$PolicyFile = ""
)
{
$urlStarterPackBase = "https://raw.githubusercontent.com/Azure-Samples/active-directory-b2c-custom-policy-starterpack/master" #/SocialAndLocalAccounts/TrustFrameworkBase.xml
function DownloadFile ( $Url, $LocalPath ) {
$p = $Url -split("/")
$filename = $p[$p.Length-1]
$LocalFile = "$LocalPath/$filename"
Write-Host "Downloading $Url to $LocalFile"
$webclient = New-Object System.Net.WebClient
$webclient.DownloadFile($Url,$LocalFile)
}
if ( "" -eq $PolicyPath ) {
$PolicyPath = (get-location).Path
}
if ( "" -ne $PolicyFile ) {
DownloadFile "$urlStarterPackBase/$PolicyType/$PolicyFile" $PolicyPath
} else {
DownloadFile "$urlStarterPackBase/$PolicyType/TrustFrameworkBase.xml" $PolicyPath
DownloadFile "$urlStarterPackBase/$PolicyType/TrustFrameworkExtensions.xml" $PolicyPath
DownloadFile "$urlStarterPackBase/$PolicyType/SignUpOrSignin.xml" $PolicyPath
DownloadFile "$urlStarterPackBase/$PolicyType/PasswordReset.xml" $PolicyPath
DownloadFile "$urlStarterPackBase/$PolicyType/ProfileEdit.xml" $PolicyPath
}
}
<#
.SYNOPSIS
Starts a new B2C Custom Policies project
.DESCRIPTION
Wrapper command that downloads the starter pack, auto-edit the details, prepares custom attributes, upgrades to lates html page versions and enables javascript and sets the AppInsight Instrumentation Key.
.PARAMETER TenantName
TenantName to use for auto-editing the policy files.
.PARAMETER PolicyPath
Path to store the downloades files. Current Directory is default
.PARAMETER PolicyType
The type of policies to download. SocialAndLocalAccounts is default
.PARAMETER PolicyPrefix
Prefix to insert in the PolicyIds, so that B2C_1A_TrustFrameworkExtensions becomes B2C_1A_<prefix>_TrustFrameworkExtensions
.EXAMPLE
New-AzureADB2CPolicyProject -PolicyPrefix "demo"
.EXAMPLE
New-AzureADB2CPolicyProject -PolicyPrefix "demo" -PolicyType "SocialAndLocalWithMfa"
.EXAMPLE
New-AzureADB2CPolicyProject -PolicyPrefix "demo" -PolicyType "SocialAndLocalWithMfa" -NoCustomAttributes:$True
#>
function New-AzureADB2CPolicyProject
(
[Parameter(Mandatory=$false)][Alias('t')][string]$TenantName = "",
[Parameter(Mandatory=$false)][Alias('p')][string]$PolicyPath = "",
[Parameter(Mandatory=$false)][Alias('b')][string]$PolicyType = "SocialAndLocalAccounts",
[Parameter(Mandatory=$false)][Alias('x')][string]$PolicyPrefix = "",
[Parameter(Mandatory=$false)][switch]$NoCustomAttributes = $False,
[Parameter(Mandatory=$false)][boolean]$AzureCli = $False # if to force Azure CLI on Windows
)
{
Get-AzureADB2CStarterPack -PolicyPath $PolicyPath -PolicyType $PolicyType
Set-AzureADB2CPolicyDetails -TenantName $TenantName -PolicyPath $PolicyPath -PolicyPrefix $PolicyPrefix
if ( $False -eq $NoCustomAttributes) {
Set-AzureADB2CCustomAttributeApp -PolicyPath $PolicyPath
}
Set-AzureADB2CAppInsights -PolicyPath $PolicyPath
Set-AzureADB2CCustomizeUX -PolicyPath $PolicyPath
}
<#
.SYNOPSIS
Auto-edit policy file details
.DESCRIPTION
Updates the policy file details to make them ready for upload to a specific tenant
.PARAMETER TenantName
TenantName to use for auto-editing the policy files.
.PARAMETER PolicyPath
Path to store the downloades files. Current Directory is default
.PARAMETER PolicyType
The type of policies to download. SocialAndLocalAccounts is default
.PARAMETER PolicyPrefix
Prefix to insert in the PolicyIds, so that B2C_1A_TrustFrameworkExtensions becomes B2C_1A_<prefix>_TrustFrameworkExtensions
.PARAMETER IefAppName
Name of IdentityExperienceFramework app. Default is IdentityExperienceFramework
.PARAMETER IefProxyAppName
Name of ProxyIdentityExperienceFramework app. Default is ProxyIdentityExperienceFramework
.PARAMETER ExtAppDisplayName
Name of the App to use for extension attributes. The default is the b2c-extensions-app
.PARAMETER Clean
Cleans the policy files and prepares them for sharing
.EXAMPLE
Set-AzureADB2CPolicyDetails -PolicyPrefix "demo"
.EXAMPLE
Set-AzureADB2CPolicyDetails -PolicyPrefix "demo" -ExtAppDisplayName "ext-app-name"
.EXAMPLE
Set-AzureADB2CPolicyDetails -Clean
#>
function Set-AzureADB2CPolicyDetails
(
[Parameter(Mandatory=$false)][Alias('t')][string]$TenantName = "",
[Parameter(Mandatory=$false)][Alias('p')][string]$PolicyPath = "",
[Parameter(Mandatory=$false)][Alias('f')][string]$PolicyFile = "",
[Parameter(Mandatory=$false)][Alias('x')][string]$PolicyPrefix = "",
[Parameter(Mandatory=$false)][string]$IefAppName = "",
[Parameter(Mandatory=$false)][string]$IefProxyAppName = "",
[Parameter(Mandatory=$false)][string]$ExtAppDisplayName = "b2c-extensions-app", # name of add for b2c extension attributes
[Parameter(Mandatory=$false)][switch]$Clean = $False, # if to "clean" the policies and revert to "yourtenant.onmicrosoft.com" etc
[Parameter(Mandatory=$false)][boolean]$AzureCli = $False # if to force Azure CLI on Windows
)
{
if ( $True -eq $Clean ) {
$TenantName = "yourtenant.onmicrosoft.com"
$IefAppName = "IdentityExperienceFramework"
$IefProxyAppName = "ProxyIdentityExperienceFramework"
write-output "Making Policies generic for sharing"
} else {
if ( "" -eq $TenantName ) { $TenantName = $global:TenantName }
if ( "" -eq $IefAppName ) { $IefAppName = $global:b2cAppSettings.IefAppName}
if ( "" -eq $IefAppName ) { $IefAppName = "IdentityExperienceFramework"}
if ( "" -eq $IefProxyAppName ) { $IefProxyAppName = $global:b2cAppSettings.IefProxyAppName}
if ( "" -eq $IefProxyAppName ) { $IefProxyAppName = "ProxyIdentityExperienceFramework"}
}
$isMacOS = ($env:PATH -imatch "/usr/bin" ) # Mac/Linux
if ( $isMacOS ) { $AzureCLI = $True}
Function UpdatePolicyId([string]$PolicyId) {
if ( "" -ne $PolicyPrefix ) {
$PolicyId = $PolicyId.Replace("B2C_1A_", $PolicyPrefix)
}
return $PolicyId
}
Function ProcessPolicyFile( [string]$PolicyPath, [string]$file ) {
write-host "Modifying Policy file $file..."
$PolicyFileName = (Join-Path -Path $PolicyPath -ChildPath $file)
[xml]$xml = Get-Content $PolicyFileName
$xml.TrustFrameworkPolicy.PolicyId = UpdatePolicyId( $xml.TrustFrameworkPolicy.PolicyId )
$xml.TrustFrameworkPolicy.PublicPolicyUri = UpdatePolicyId( $xml.TrustFrameworkPolicy.PublicPolicyUri.Replace( $xml.TrustFrameworkPolicy.TenantId, $TenantName) )
$xml.TrustFrameworkPolicy.TenantId = $TenantName
if ( $null -ne $xml.TrustFrameworkPolicy.BasePolicy ) {
$xml.TrustFrameworkPolicy.BasePolicy.TenantId = $TenantName
$xml.TrustFrameworkPolicy.BasePolicy.PolicyId = UpdatePolicyId( $xml.TrustFrameworkPolicy.BasePolicy.PolicyId )
}
if ( $xml.TrustFrameworkPolicy.PolicyId -imatch "TrustFrameworkExtensions" ) {
foreach( $cp in $xml.TrustFrameworkPolicy.ClaimsProviders.ClaimsProvider ) {
$cp.DisplayName
if ( "Local Account SignIn" -eq $cp.DisplayName ) {
foreach( $tp in $cp.TechnicalProfiles ) {
foreach( $metadata in $tp.TechnicalProfile.Metadata ) {
foreach( $item in $metadata.Item ) {
if ( "client_id" -eq $item.Key ) {
$item.'#text' = $AppIdIEFProxy
}
if ( "IdTokenAudience" -eq $item.Key ) {
$item.'#text' = $AppIdIEF
}
}
}
foreach( $ic in $tp.TechnicalProfile.InputClaims.InputClaim ) {
if ( "client_id" -eq $ic.ClaimTypeReferenceId ) {
$ic.DefaultValue = $AppIdIEFProxy
}
if ( "resource_id" -eq $ic.ClaimTypeReferenceId ) {
$ic.DefaultValue = $AppIdIEF
}
}
}
} else {
if ( $True -eq $Clean ) {
foreach( $tp in $cp.TechnicalProfiles ) {
foreach( $metadata in $tp.TechnicalProfile.Metadata ) {
foreach( $item in $metadata.Item ) {
if ( "client_id" -eq $item.Key ) {
$item.'#text' = "...add your client_id here..."
}
}
}
}
}
}
if ( "" -ne $ExtAppDisplayName ) {
foreach( $tp in $cp.TechnicalProfiles ) {
if ( "AAD-Common" -eq $tp.TechnicalProfile.Id[0] -or "AAD-Common" -eq $tp.TechnicalProfile.Id) {
foreach( $metadata in $tp.TechnicalProfile.Metadata ) {
foreach( $item in $metadata.Item ) {
if ( "ClientId" -eq $item.Key ) {
$item.'#text' = $appExtAppId
}
if ( "ApplicationObjectId" -eq $item.Key ) {
$item.'#text' = $appExtObjectId
}
}
}
}
}
}
}
}
if ( $True -eq $Clean ) {
foreach( $rp in $xml.TrustFrameworkPolicy.RelyingParty ) {
if ( $null -ne $rp.UserJourneyBehaviors -and $null -ne $rp.UserJourneyBehaviors.JourneyInsights ) {
$rp.UserJourneyBehaviors.JourneyInsights.InstrumentationKey = "...add your key here..."
}
}
}
$xml.Save($PolicyFileName)
}
# process all XML Policy files and update elements and attributes to our values
Function ProcessPolicyFiles( [string]$PolicyPath ) {
$files = get-childitem -path $policypath -name -include *.xml | Where-Object {! $_.PSIsContainer }
foreach( $file in $files ) {
ProcessPolicyFile $PolicyPath $file
}
}
<##>
$tenantID = ""
$appExtAppId = ""
$appExtObjectId = ""
if ( $True -eq $Clean ) {
$AppIdIEF = "IdentityExperienceFrameworkAppId"
$AppIdIEFProxy = "ProxyIdentityExperienceFrameworkAppId"
$appExtAppId = "b2c-extension-app AppId"
$appExtObjectId = "b2c-extension-app objectId"
} else {
$resp = Invoke-RestMethod -Uri "https://login.windows.net/$TenantName/v2.0/.well-known/openid-configuration"
$tenantID = $resp.authorization_endpoint.Split("/")[3]
<##>
if ( "" -eq $tenantID ) {
write-host "Unknown Tenant"
return
}
write-host "Tenant: `t$tenantName`nTenantID:`t$tenantId"
<##>
write-host "Getting AppID's for $IefAppName / $IefProxyAppName"
if ( $True -eq $AzureCli ) {
$AppIdIEF = (az ad app list --display-name $iefAppName | ConvertFrom-json).AppId
$AppIdIEFProxy = (az ad app list --display-name $iefProxyAppName | ConvertFrom-json).AppId
if ( "" -ne $ExtAppDisplayName ) {
write-output "Getting AppID's for $ExtAppDisplayName"
$appExt = (az ad app list --display-name $ExtAppDisplayName | ConvertFrom-json)
$appExtAppId = $appExt.AppId
$appExtObjectId = $appExt.objectId
}
} else {
$AppIdIEF = (Get-AzureADApplication -Filter "DisplayName eq '$iefAppName'").AppId
$AppIdIEFProxy = (Get-AzureADApplication -Filter "DisplayName eq '$iefProxyAppName'").AppId
if ( "" -ne $ExtAppDisplayName ) {
write-output "Getting AppID's for $ExtAppDisplayName"
$appExt = Get-AzureADApplication -SearchString $ExtAppDisplayName
write-output $appExt.AppID
$appExtAppId = $appExt.AppId
$appExtObjectId = $appExt.objectId
}
}
}
if ( "" -eq $PolicyPath ) {
$PolicyPath = (get-location).Path
}
if ( ! $PolicyPrefix.StartsWith("B2C_1A_") ) {
$PolicyPrefix = "B2C_1A_$PolicyPrefix"
}
if ( ! $PolicyPrefix.EndsWith("_") ) {
$PolicyPrefix = "$($PolicyPrefix)_"
}
#
if ( "" -ne $PolicyFile ) {
ProcessPolicyFile $PolicyPath $PolicyFile
} else {
ProcessPolicyFiles $PolicyPath
}
}
<#
.SYNOPSIS
Gets a B2C Custom Policy
.DESCRIPTION
Gets a B2C Custom Policy from the tenant policy store by PolicyId
.PARAMETER TenantName
TenantName to use for auto-editing the policy files.
.PARAMETER PolicyId
PolicyId in the B2C tenant
.PARAMETER PolicyFile
Filename to store policy in
.PARAMETER AppID
AppID for your client_credentials. Default is to use $env:B2CAppID
.PARAMETER AppKey
secret for your client_credentials. Default is to use $env:B2CAppKey
.EXAMPLE
Get-AzureADB2CPolicyId -PolicyId "B2C_1A_demo_TrustFrameworkExtensions"
#>
function Get-AzureADB2CPolicyId
(
[Parameter(Mandatory=$false)][Alias('p')][string]$PolicyId = "",
[Parameter(Mandatory=$false)][Alias('f')][string]$PolicyFile = "",
[Parameter(Mandatory=$false)][Alias('t')][string]$TenantName = "",
[Parameter(Mandatory=$false)][Alias('a')][string]$AppID = "",
[Parameter(Mandatory=$false)][Alias('k')][string]$AppKey = "",
[Parameter(Mandatory=$false)][boolean]$AzureCli = $False # if to force Azure CLI on Windows
)
{
$oauth = $null
if ( "" -eq $AppID ) { $AppID = $env:B2CAppId }
if ( "" -eq $AppKey ) { $AppKey = $env:B2CAppKey }
if ( "" -eq $TenantName ) { $TenantName = $global:TenantName }
$isMacOS = ($env:PATH -imatch "/usr/bin" ) # Mac/Linux
if ( $isMacOS ) { $AzureCLI = $True}
# either try and use the tenant name passed or grab the tenant from current session
<##>
$tenantID = ""
$resp = Invoke-RestMethod -Uri "https://login.windows.net/$TenantName/v2.0/.well-known/openid-configuration"
$tenantID = $resp.authorization_endpoint.Split("/")[3]
<##>
<##>
if ( "" -eq $tenantID ) {
write-host "Unknown Tenant"
return
}
#write-host "Tenant: `t$tenantName`nTenantID:`t$tenantId"
# check the B2C Graph App passed
if ( $True -eq $AzureCli ) {
$app = (az ad app show --id $AppID | ConvertFrom-json)
} else {
$app = Get-AzureADApplication -Filter "AppID eq '$AppID'"
}
if ( $null -eq $app ) {
write-host "App not found in B2C tenant: $AppID"
return
} else {
#write-host "`Authenticating as App $($app.DisplayName), AppID $AppID"
}
# https://docs.microsoft.com/en-us/azure/active-directory/users-groups-roles/directory-assign-admin-roles#b2c-user-flow-administrator
# get an access token for the B2C Graph App
$oauthBody = @{grant_type="client_credentials";resource="https://graph.microsoft.com/";client_id=$AppID;client_secret=$AppKey;scope="Policy.Read.TrustFramework"}
$oauth = Invoke-RestMethod -Method Post -Uri "https://login.microsoft.com/$tenantName/oauth2/token?api-version=1.0" -Body $oauthBody
#write-host "Getting policy $PolicyId..."
$url = "https://graph.microsoft.com/beta/trustFramework/policies/$PolicyId/`$value"
$resp = Invoke-RestMethod -Method GET -Uri $url -ContentType "application/xml" -Headers @{'Authorization'="$($oauth.token_type) $($oauth.access_token)"}
if ( "" -eq $PolicyFile ) {
return $resp.OuterXml
} else {
Set-Content -Path $PolicyFile -Value $resp.OuterXml
}
}
<#
.SYNOPSIS
Lists B2C Custom Policies
.DESCRIPTION
Lists B2C Custom Policies from the tenant policy
.PARAMETER TenantName
TenantName to use for auto-editing the policy files.
.PARAMETER PolicyId
PolicyId in the B2C tenant
.PARAMETER AppID
AppID for your client_credentials. Default is to use $env:B2CAppID
.PARAMETER AppKey
secret for your client_credentials. Default is to use $env:B2CAppKey
.EXAMPLE
List-AzureADB2CPolicyId
#>
function List-AzureADB2CPolicyIds
(
[Parameter(Mandatory=$false)][Alias('t')][string]$TenantName = "",
[Parameter(Mandatory=$false)][Alias('a')][string]$AppID = "",
[Parameter(Mandatory=$false)][Alias('k')][string]$AppKey = "",
[Parameter(Mandatory=$false)][boolean]$AzureCli = $False # if to force Azure CLI on Windows
)
{
$oauth = $null
if ( "" -eq $AppID ) { $AppID = $env:B2CAppId }
if ( "" -eq $AppKey ) { $AppKey = $env:B2CAppKey }
if ( "" -eq $TenantName ) { $TenantName = $global:TenantName }
$isMacOS = ($env:PATH -imatch "/usr/bin" ) # Mac/Linux
if ( $isMacOS ) { $AzureCLI = $True}
# either try and use the tenant name passed or grab the tenant from current session
<##>
$tenantID = ""
$resp = Invoke-RestMethod -Uri "https://login.windows.net/$TenantName/v2.0/.well-known/openid-configuration"
$tenantID = $resp.authorization_endpoint.Split("/")[3]
<##>
<##>
if ( "" -eq $tenantID ) {
write-host "Unknown Tenant"
return
}
#write-host "Tenant: `t$tenantName`nTenantID:`t$tenantId"
# check the B2C Graph App passed
if ( $True -eq $AzureCli ) {
$app = (az ad app show --id $AppID | ConvertFrom-json)
} else {
$app = Get-AzureADApplication -Filter "AppID eq '$AppID'"
}
if ( $null -eq $app ) {
write-host "App not found in B2C tenant: $AppID"
return
} else {
#write-host "`Authenticating as App $($app.DisplayName), AppID $AppID"
}
# https://docs.microsoft.com/en-us/azure/active-directory/users-groups-roles/directory-assign-admin-roles#b2c-user-flow-administrator
# get an access token for the B2C Graph App
$oauthBody = @{grant_type="client_credentials";resource="https://graph.microsoft.com/";client_id=$AppID;client_secret=$AppKey;scope="Policy.Read.TrustFramework"}
$oauth = Invoke-RestMethod -Method Post -Uri "https://login.microsoft.com/$tenantName/oauth2/token?api-version=1.0" -Body $oauthBody
$url = "https://graph.microsoft.com/beta/trustFramework/policies"
$resp = Invoke-RestMethod -Method GET -Uri $url -ContentType "application/xml" -Headers @{'Authorization'="$($oauth.token_type) $($oauth.access_token)"}
$resp.value | ConvertTo-json
}
<#
.SYNOPSIS
Uploads B2C Custom Policies
.DESCRIPTION
Uploads B2C Custom Policies from local path to B2C tenant
.PARAMETER TenantName
TenantName to use for auto-editing the policy files.
.PARAMETER PolicyPath
Path to policies. Default is current directory
.PARAMETER PolicyFile
Policy filename if uploading specific file. Default is all policy files in PolicyPath
.PARAMETER AppID
AppID for your client_credentials. Default is to use $env:B2CAppID
.PARAMETER AppKey
secret for your client_credentials. Default is to use $env:B2CAppKey
.EXAMPLE
Deploy-AzureADB2CPolicyToTenant
.EXAMPLE
Deploy-AzureADB2CPolicyToTenant -PolicyFile ".\SignUpOrSignin.xml"
#>
function Deploy-AzureADB2CPolicyToTenant
(
[Parameter(Mandatory=$false)][Alias('p')][string]$PolicyPath = "",
[Parameter(Mandatory=$false)][Alias('f')][string]$PolicyFile = "",
[Parameter(Mandatory=$false)][Alias('t')][string]$TenantName = "",
[Parameter(Mandatory=$false)][Alias('a')][string]$AppID = "",
[Parameter(Mandatory=$false)][Alias('k')][string]$AppKey = "",
[Parameter(Mandatory=$false)][boolean]$AzureCli = $False # if to force Azure CLI on Windows
)
{
$oauth = $null
if ( "" -eq $AppID ) { $AppID = $env:B2CAppId }
if ( "" -eq $AppKey ) { $AppKey = $env:B2CAppKey }
if ( "" -eq $TenantName ) { $TenantName = $global:TenantName }
$isMacOS = ($env:PATH -imatch "/usr/bin" ) # Mac/Linux
if ( $isMacOS ) { $AzureCLI = $True}
# enumerate all XML files in the specified folders and create a array of objects with info we need
Function EnumPoliciesFromPath( [string]$PolicyPath ) {
$files = get-childitem -path $policypath -name -include *.xml | Where-Object {! $_.PSIsContainer }
$arr = @()
foreach( $file in $files ) {
#write-output "Reading Policy XML file $file..."
$PolicyFile = (Join-Path -Path $PolicyPath -ChildPath $file)
$PolicyData = Get-Content $PolicyFile
[xml]$xml = $PolicyData
if ($null -ne $xml.TrustFrameworkPolicy) {
$policy = New-Object System.Object
$policy | Add-Member -type NoteProperty -name "PolicyId" -Value $xml.TrustFrameworkPolicy.PolicyId
$policy | Add-Member -type NoteProperty -name "BasePolicyId" -Value $xml.TrustFrameworkPolicy.BasePolicy.PolicyId
$policy | Add-Member -type NoteProperty -name "Uploaded" -Value $false
$policy | Add-Member -type NoteProperty -name "FilePath" -Value $PolicyFile
$policy | Add-Member -type NoteProperty -name "xml" -Value $xml
$policy | Add-Member -type NoteProperty -name "PolicyData" -Value $PolicyData
$policy | Add-Member -type NoteProperty -name "HasChildren" -Value $null
$arr += $policy
}
}
return $arr
}
# process each Policy object in the array. For each that has a BasePolicyId, follow that dependency link
# first call has to be with BasePolicyId null (base/root policy) for this to work
Function ProcessPolicies( $arrP, $BasePolicyId ) {
foreach( $p in $arrP ) {
if ( $p.xml.TrustFrameworkPolicy.TenantId -ne $TenantName ) {
write-output "$($p.PolicyId) has wrong tenant configured $($p.xml.TrustFrameworkPolicy.TenantId) - skipped"
} else {
if ( $BasePolicyId -eq $p.BasePolicyId -and $p.Uploaded -eq $false ) {
# upload this one
UploadPolicy $p.PolicyId $p.PolicyData
$p.Uploaded = $true
# process all policies that has a ref to this one
ProcessPolicies $arrP $p.PolicyId
}
}
}
}
# invoke the Graph REST API to upload the Policy
Function UploadPolicy( [string]$PolicyId, [string]$PolicyData) {
# https://docs.microsoft.com/en-us/graph/api/trustframework-put-trustframeworkpolicy?view=graph-rest-beta
# upload the Custom Policy
write-host "Uploading policy $PolicyId..."
$url = "https://graph.microsoft.com/beta/trustFramework/policies/$PolicyId/`$value"
try {
$resp = Invoke-RestMethod -Method PUT -Uri $url -ContentType "application/xml" -Headers @{'Authorization'="$($oauth.token_type) $($oauth.access_token)"} -Body $PolicyData
write-host $resp.TrustFrameworkPolicy.PublicPolicyUri
} catch {
$streamReader = [System.IO.StreamReader]::new($_.Exception.Response.GetResponseStream())
$streamReader.BaseStream.Position = 0
$streamReader.DiscardBufferedData()
$errResp = $streamReader.ReadToEnd()
$streamReader.Close()
write-host $errResp -ForegroundColor "Red" -BackgroundColor "Black"
}
}
# either try and use the tenant name passed or grab the tenant from current session
<##>
$tenantID = ""
$resp = Invoke-RestMethod -Uri "https://login.windows.net/$TenantName/v2.0/.well-known/openid-configuration"
$tenantID = $resp.authorization_endpoint.Split("/")[3]
<##>
<##>
if ( "" -eq $tenantID ) {
write-host "Unknown Tenant"
return
}
write-host "Tenant: `t$tenantName`nTenantID:`t$tenantId"
# check the B2C Graph App passed
if ( $True -eq $AzureCli ) {
$app = (az ad app show --id $AppID | ConvertFrom-json)
} else {
$app = Get-AzureADApplication -Filter "AppID eq '$AppID'"
}
if ( $null -eq $app ) {
write-host "App not found in B2C tenant: $AppID"
return
} else {
write-host "`Authenticating as App $($app.DisplayName), AppID $AppID"
}
<##>
if ( "" -eq $PolicyPath ) {
$PolicyPath = (get-location).Path
}
# https://docs.microsoft.com/en-us/azure/active-directory/users-groups-roles/directory-assign-admin-roles#b2c-user-flow-administrator
# get an access token for the B2C Graph App
$oauthBody = @{grant_type="client_credentials";resource="https://graph.microsoft.com/";client_id=$AppID;client_secret=$AppKey;scope="Policy.ReadWrite.TrustFramework"}
$oauth = Invoke-RestMethod -Method Post -Uri "https://login.microsoft.com/$tenantName/oauth2/token?api-version=1.0" -Body $oauthBody
if ( "" -ne $PolicyFile ) {
# upload a single file
$PolicyData = Get-Content $PolicyFile #
[xml]$xml = $PolicyData
UploadPolicy $xml.TrustFrameworkPolicy.PolicyId $PolicyData
} else {
# load the XML Policy files
$arr = EnumPoliciesFromPath $PolicyPath
# find out who is/are the root in inheritance chain so we know which to upload first
foreach( $p in $arr ) {
$p.HasChildren = ( $null -ne ($arr | where {$_.PolicyId -eq $p.BasePolicyId}) )
}
# upload policies - start with those who are root(s)
foreach( $p in $arr ) {
if ( $p.HasChildren -eq $False ) {
ProcessPolicies $arr $p.BasePolicyId
}
}
# check what hasn't been uploaded
foreach( $p in $arr ) {
if ( $p.Uploaded -eq $false ) {
write-output "$($p.PolicyId) has a refence to $($p.BasePolicyId) which doesn't exists in the folder - not uploaded"
}
}
}
}
<#
.SYNOPSIS
Sets the B2C extension attributes app
.DESCRIPTION
Sets the AppID and objectId for extension attributes in the B2C Custom Policies
.PARAMETER TenantName
TenantName to use for auto-editing the policy files.
.PARAMETER PolicyPath
Path to policies. Default is current directory
.PARAMETER PolicyFile
Filename of TrustFrameworkExtensions.xml if it has a non-default name.
.PARAMETER client_id
AppID for the app that handles extension attributes for your policy
.PARAMETER object_id
objectID for the app that handles extension attributes for your policy
.PARAMETER AppDisplayName
If you name the app to handle the extension attributes, the command will get the client_id and objectId for that app.
.EXAMPLE
Set-AzureADB2CCustomAttributeApp
.EXAMPLE
Set-AzureADB2CCustomAttributeApp -AppDisplayName "my-ext-app"
#>
function Set-AzureADB2CCustomAttributeApp
(
[Parameter(Mandatory=$false)][Alias('p')][string]$PolicyPath = "",
[Parameter(Mandatory=$false)][Alias('c')][string]$client_id = "", # client_id/AppId of the app handeling custom attributes
[Parameter(Mandatory=$false)][Alias('a')][string]$objectId = "", # objectId of the same app
[Parameter(Mandatory=$false)][Alias('n')][string]$AppDisplayName = "", # objectId of the same app
[Parameter(Mandatory=$false)][Alias('f')][string]$PolicyFile = "TrustFrameworkExtensions.xml", # if the Extensions file has a different name
[Parameter(Mandatory=$false)][boolean]$AzureCli = $False # if to force Azure CLI on Windows
)
{
$isMacOS = ($env:PATH -imatch "/usr/bin" ) # Mac/Linux
if ( $isMacOS ) { $AzureCLI = $True}
if ( "" -eq $PolicyPath ) {
$PolicyPath = (get-location).Path
}
[xml]$ext =Get-Content -Path "$PolicyPath/$PolicyFile" -Raw
$tpId = "AAD-Common"
$claimsProviderXml=@"
<ClaimsProvider>
<DisplayName>Azure Active Directory</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="AAD-Common">
<Metadata>
<!--Insert b2c-extensions-app application ID here, for example: 11111111-1111-1111-1111-111111111111-->
<Item Key="ClientId">{client_id}</Item>
<!--Insert b2c-extensions-app application ObjectId here, for example: 22222222-2222-2222-2222-222222222222-->
<Item Key="ApplicationObjectId">{objectId}</Item>
</Metadata>
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
"@
if ( $ext.TrustFrameworkPolicy.ClaimsProviders.InnerXml -imatch $tpId ) {
write-output "TechnicalProfileId $tpId already exists in policy"
return
}
# if no client_id given, use the standard b2c-extensions-app
if ( "" -eq $client_id ) {
if ( "" -eq $AppDisplayName ) { $AppDisplayName = "b2c-extensions-app"}
write-output "Using $AppDisplayName"
if ( $True -eq $AzureCli ) {
$appExt = (az ad app list --display-name $AppDisplayName | ConvertFrom-json)
} else {
$appExt = Get-AzureADApplication -SearchString $AppDisplayName
}
$client_id = $appExt.AppId
$objectId = $appExt.objectId
}
write-output "Adding TechnicalProfileId $tpId"
$claimsProviderXml = $claimsProviderXml.Replace("{client_id}", $client_id)
$claimsProviderXml = $claimsProviderXml.Replace("{objectId}", $objectId)
$ext.TrustFrameworkPolicy.ClaimsProviders.innerXml = $ext.TrustFrameworkPolicy.ClaimsProviders.innerXml + $claimsProviderXml
$ext.Save("$PolicyPath/$PolicyFile")
}
<#
.SYNOPSIS
Prepares the policies for UX customizations
.DESCRIPTION
Prepares the policies for UX customizations via setting page version to latest and enabling javascript
.PARAMETER PolicyPath
Path to policies. Default is current directory
.PARAMETER RelyingPartyFileName
Name of Replying Party file. Default is SignupOrSignin.xml
.PARAMETER ExtPolicyFileName
Name of TrustFrameworkExtensions file. Default is TrustFrameworkExtensions.xml
.PARAMETER BasePolicyFileName
Name of TrustFrameworBase file. Default is TrustFrameworkBase.xml
.PARAMETER DownloadHtmlTemplates
If to download the standard html templates to local directory
.PARAMETER HtmlFolderName
Local folder name for downloading html files. Default is "html"
.EXAMPLE
Set-AzureADB2CCustomizeUX
.EXAMPLE
Set-AzureADB2CCustomizeUX -FullContentDefinition:$True
.EXAMPLE
Set-AzureADB2CCustomizeUX -DownloadHtmlTemplates
#>
function Set-AzureADB2CCustomizeUX
(
[Parameter(Mandatory=$false)][Alias('p')][string]$PolicyPath = "",
[Parameter(Mandatory=$false)][Alias('r')][string]$RelyingPartyFileName = "SignUpOrSignin.xml",
[Parameter(Mandatory=$false)][Alias('b')][string]$BasePolicyFileName = "TrustFrameworkBase.xml",
[Parameter(Mandatory=$false)][Alias('e')][string]$ExtPolicyFileName = "TrustFrameworkExtensions.xml",
[Parameter(Mandatory=$false)][Alias('d')][switch]$DownloadHtmlTemplates = $false,
[Parameter(Mandatory=$false)][Alias('h')][string]$HtmlFolderName = "html",
[Parameter(Mandatory=$false)][Alias('u')][string]$urlBaseUx = "",
[Parameter(Mandatory=$false)][switch]$FullContentDefinition = $False
)
{
[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
function DownloadFile ( $Url, $LocalPath ) {
$p = $Url -split("/")
$filename = $p[$p.Length-1]
$LocalFile = "$LocalPath\$filename"
Write-Host "Downloading $Url to $LocalFile"
$webclient = New-Object System.Net.WebClient
$webclient.DownloadFile($Url,$LocalFile)
}
if ( "" -eq $PolicyPath ) {
$PolicyPath = (get-location).Path
}
[xml]$base =Get-Content -Path "$PolicyPath\$BasePolicyFileName" -Raw
[xml]$ext =Get-Content -Path "$PolicyPath\$ExtPolicyFileName" -Raw
$tenantShortName = $base.TrustFrameworkPolicy.TenantId.Split(".")[0]
$cdefs = $base.TrustFrameworkPolicy.BuildingBlocks.ContentDefinitions.Clone()
if ( $true -eq $DownloadHtmlTemplates) {
$ret = New-Item -Path $PolicyPath -Name "$HtmlFolderName" -ItemType "directory" -ErrorAction SilentlyContinue
}
<##>
foreach( $contDef in $cdefs.ContentDefinition ) {
switch( $contDef.DataUri ) {
"urn:com:microsoft:aad:b2c:elements:globalexception:1.0.0" { $contDef.DataUri = "urn:com:microsoft:aad:b2c:elements:contract:globalexception:1.2.0" }
"urn:com:microsoft:aad:b2c:elements:globalexception:1.1.0" { $contDef.DataUri = "urn:com:microsoft:aad:b2c:elements:contract:globalexception:1.2.0" }
"urn:com:microsoft:aad:b2c:elements:idpselection:1.0.0" { $contDef.DataUri = "urn:com:microsoft:aad:b2c:elements:contract:providerselection:1.2.0" }
"urn:com:microsoft:aad:b2c:elements:multifactor:1.0.0" { $contDef.DataUri = "urn:com:microsoft:aad:b2c:elements:contract:multifactor:1.2.1" }
"urn:com:microsoft:aad:b2c:elements:multifactor:1.1.0" { $contDef.DataUri = "urn:com:microsoft:aad:b2c:elements:contract:multifactor:1.2.1" }
"urn:com:microsoft:aad:b2c:elements:unifiedssd:1.0.0" { $contDef.DataUri = "urn:com:microsoft:aad:b2c:elements:contract:unifiedssd:2.1.0" }
"urn:com:microsoft:aad:b2c:elements:unifiedssp:1.0.0" { $contDef.DataUri = "urn:com:microsoft:aad:b2c:elements:contract:unifiedssp:2.1.0" }
"urn:com:microsoft:aad:b2c:elements:selfasserted:1.0.0" { $contDef.DataUri = "urn:com:microsoft:aad:b2c:elements:contract:selfasserted:2.1.0" }
"urn:com:microsoft:aad:b2c:elements:selfasserted:1.1.0" { $contDef.DataUri = "urn:com:microsoft:aad:b2c:elements:contract:selfasserted:2.1.0" }
}
if ( $False -eq $FullContentDefinition ) {
$i1 = $contDef.InnerXml.IndexOf("<RecoveryUri" )
$i2 = $contDef.InnerXml.IndexOf("</RecoveryUri>" )
if ( $i2 -gt $i1 ) {
$contDef.InnerXml = $contDef.InnerXml.SubString(0,$i1) + $contDef.InnerXml.SubString($i2+"</RecoveryUri>".Length)
}
$i1 = $contDef.InnerXml.IndexOf("<LoadUri" )
$i2 = $contDef.InnerXml.IndexOf("</LoadUri>" )
if ( $i2 -gt $i1 ) {
$contDef.InnerXml = $contDef.InnerXml.SubString(0,$i1) + $contDef.InnerXml.SubString($i2+"</LoadUri>".Length)
}
$contDef.RemoveChild( $contDef.Metadata ) | Out-null
}
if ( $true -eq $DownloadHtmlTemplates) {
$url = "https://$tenantShortName.b2clogin.com/static" + $contDef.LoadUri.Replace("~", "")
DownloadFile $url "$PolicyPath\$HtmlFolderName"
}
if ( "" -ne $urlBaseUx ) {
$p = $contDef.LoadUri -split("/")
$filename = $p[$p.Length-1]
$contDef.LoadUri = "$urlBaseUx/$filename"
}
}
if ( $null -ne $ext.TrustFrameworkPolicy.BuildingBlocks.ContentDefinitions ) {
$ext.TrustFrameworkPolicy.BuildingBlocks.RemoveChild( $ext.TrustFrameworkPolicy.BuildingBlocks.ContentDefinitions )
}
<##>
$ext.TrustFrameworkPolicy.InnerXml = $ext.TrustFrameworkPolicy.InnerXml.Replace("</BuildingBlocks>", "<ContentDefinitions>" + $cdefs.InnerXml + "</ContentDefinitions></BuildingBlocks>")
$ext.Save("$PolicyPath\$ExtPolicyFileName")
<##>
if ( "" -ne $RelyingPartyFileName ) {
[xml]$rp =Get-Content -Path "$PolicyPath\$RelyingPartyFileName" -Raw
# don't have UserJourneyBehaviors - add it directly after DefaultUserJourney element
if ( $null -eq $rp.TrustFrameworkPolicy.RelyingParty.UserJourneyBehaviors ) {
$rp.TrustFrameworkPolicy.RelyingParty.InnerXml = $rp.TrustFrameworkPolicy.RelyingParty.InnerXml.Replace("<TechnicalProfile", "<UserJourneyBehaviors><ScriptExecution>Allow</ScriptExecution></UserJourneyBehaviors><TechnicalProfile")
} else {
$rp.TrustFrameworkPolicy.RelyingParty.InnerXml = $rp.TrustFrameworkPolicy.RelyingParty.InnerXml.Replace("</UserJourneyBehaviors>", "<ScriptExecution>Allow</ScriptExecution></UserJourneyBehaviors>")
}
$rp.Save("$PolicyPath\$RelyingPartyFileName")
}
<##>
}
<#
.SYNOPSIS
Runs a B2C Custom Policy
.DESCRIPTION
Creates a working url for testing and launches a browser to test a B2C Custom Policy
.PARAMETER PolicyFile
Policy to run
.PARAMETER WebAppName
Name of WebApp to use as client_id.
.PARAMETER redirect_uri
The redirect_uri of the request. Default is https://jwt.ms
.PARAMETER response_types
response_types for the request. Default is "id_token"
.PARAMETER scopes
Scopes for the request. Default is "openid"
.PARAMETER Chrome
Use the Chrome browser. Default is your default browser
.PARAMETER Edge
Use the Edge browser. Default is your default browser
.PARAMETER Firefox
Use the Firefox browser. Default is your default browser
.PARAMETER Incognito
Start the browser in incognito/inprivate mode (default). Specify -Incognito:$False to disable
.PARAMETER NewWindow
Start the browser in a new window (default). Specify -NewWindow:$False to disable
.PARAMETER QueryString
Extra QueryString to add, for instance "&[email protected]"
.PARAMETER Prompt
What prompt to use. Default is "login". Accepted values are none, login and not specified
.EXAMPLE
Test-AzureADB2CPolicy -n "ABC-WebApp" -p ".\SignUpOrSignin.xml"
.EXAMPLE
Test-AzureADB2CPolicy -n "ABC-WebApp" -p ".\SignUpOrSignin.xml" -Firefox
.EXAMPLE
Test-AzureADB2CPolicy -n "ABC-WebApp" -p ".\SignUpOrSignin.xml" -Firefox -Incognito:$False -NewWindow:$False
#>
function Test-AzureADB2CPolicy
(
[Parameter(Mandatory=$false)][Alias('p')][string]$PolicyFile,
[Parameter(Mandatory=$false)][Alias('i')][string]$PolicyId,
[Parameter(Mandatory=$false)][Alias('n')][string]$WebAppName = "",
[Parameter(Mandatory=$false)][Alias('r')][string]$redirect_uri = "https://jwt.ms",
[Parameter(Mandatory=$false)][Alias('s')][string]$scopes = "",
[Parameter(Mandatory=$false)][Alias('t')][string]$response_type = "id_token",
[Parameter(Mandatory=$false)][Alias('b')][string]$browser = "", # Chrome, Edge or Firefox
[Parameter(Mandatory=$false)][Alias('q')][string]$QueryString = "", # extra querystring params
[Parameter(Mandatory=$false)][string]$Prompt = "login",
[Parameter(Mandatory=$false)][switch]$Chrome = $False,
[Parameter(Mandatory=$false)][switch]$Edge = $False,
[Parameter(Mandatory=$false)][switch]$Firefox = $False,
[Parameter(Mandatory=$false)][switch]$Incognito = $True,
[Parameter(Mandatory=$false)][switch]$NewWindow = $True,
[Parameter(Mandatory=$false)][switch]$Metadata = $False,
[Parameter(Mandatory=$false)][switch]$SAMLIDP = $False,
[Parameter(Mandatory=$false)][boolean]$AzureCli = $False # if to force Azure CLI on Windows
)
{
$isMacOS = ($env:PATH -imatch "/usr/bin" ) # Mac/Linux
if ( $isMacOS ) { $AzureCLI = $True}
$isSAML = $false
$tenantName = $global:TenantName
if ( "" -eq $PolicyId ) {
if (!(Test-Path $PolicyFile -PathType leaf)) {
write-error "File does not exists: $PolicyFile"
return
}
[xml]$xml = Get-Content $PolicyFile
$PolicyId = $xml.TrustFrameworkPolicy.PolicyId
if ( "" -eq $tenantName ) {
$tenantName = $xml.TrustFrameworkPolicy.TenantId
}
if ( "SAML2"-ne $xml.TrustFrameworkPolicy.RelyingParty.TechnicalProfile.Protocol.Name ) {
$isSAML = $false
} else {
$isSAML = $true
}
}
if ( "" -eq $WebAppName ) {
if ( $isSAML ) {
$WebAppName = $global:b2cAppSettings.SAMLTestAppName
} else {
$WebAppName = $global:b2cAppSettings.TestAppName
}
}
if ( $QueryString.length -gt 0 -and $QueryString.StartsWith("&") -eq $False ) {
$QueryString = "&$QueryString"
}
$hostName = "{0}.b2clogin.com" -f $tenantName.Split(".")[0]
if ( $global:B2CCustomDomain.Length -gt 0) {
$hostName = $global:B2CCustomDomain
write-host "Using B2C Custom Domain" $global:B2CCustomDomain
}
write-host "Getting test app $WebAppName"
if ( $True -eq $AzureCli ) {