-
Notifications
You must be signed in to change notification settings - Fork 249
Expand file tree
/
Copy patho365-connect-spo-cert.ps1
More file actions
1806 lines (1567 loc) · 93.4 KB
/
Copy patho365-connect-spo-cert.ps1
File metadata and controls
1806 lines (1567 loc) · 93.4 KB
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
Connect to the SharePoint Online admin center using certificate-based (app-only) authentication,
or generate and provision the certificate/Entra ID app required to do so.
.DESCRIPTION
This script operates in exactly one of two mutually exclusive modes:
MODE 1: -GenerateLocalCertificate
Creates a self-signed RSA-2048 certificate in the CurrentUser\My store and exports the
public .cer file (and optionally a .pfx with private key). When combined with
-ProvisionEntraApp it also:
1. Authenticates to Microsoft Graph via the device-code flow (delegated, interactive).
2. Creates (or reuses) an Entra ID app registration.
3. Uploads the certificate as a key credential on that app.
4. Grants and consents SharePoint Sites.FullControl.All plus Microsoft Graph
Application.Read.All and Group.Read.All application permissions.
5. Saves the resulting tenant/app/thumbprint details to a JSON profile map so future
connections need no parameters.
MODE 2: -UseCertificateAuth
Connects to the SharePoint admin center non-interactively using an existing app + certificate.
Connection values are resolved in this order of precedence:
1. Explicit parameters (-Tenant, -AdminUrl, -AppId, -CertificateThumbprint).
2. A matching profile in the JSON profile map (see -CertificateMapPath).
3. Derivation/discovery (admin URL derived from tenant name; thumbprint discovered in the
local certificate store; missing private keys re-imported from an exported PFX).
.PARAMETER noprompt
Suppress all interactive prompts (for automation). Ambiguous situations become errors instead.
.PARAMETER noupdate
Skip the check for a newer version of the SharePoint Online PowerShell module.
.PARAMETER enableLog
Write a transcript log file (o365-connect-spo-admin.txt) in the script's parent directory.
.PARAMETER GenerateLocalCertificate
Mode 1: generate a self-signed certificate for app-only authentication.
.PARAMETER UseCertificateAuth
Mode 2: connect to the SharePoint admin center using an existing app registration and certificate.
.PARAMETER GeneratedCertSubject
Subject (CN) for the generated certificate. Default: O365-SPO-AppAuth.
.PARAMETER GeneratedCertYearsValid
Validity period in years for the generated certificate. Default: 2.
.PARAMETER GeneratedCertOutputPath
Folder for exported certificate files. Defaults to the parent of the script directory.
.PARAMETER ExportGeneratedPfx
Also export the private key as a .pfx file (needed to use the certificate on other machines).
.PARAMETER GeneratedPfxPassword
SecureString password protecting the exported PFX. If omitted interactively you are prompted;
with -noprompt an EMPTY password is used (a warning is shown).
.PARAMETER Tenant
Tenant identifier: a GUID, .onmicrosoft.com domain, or custom domain. Used for authentication
and for deriving the admin URL when -AdminUrl is not supplied.
.PARAMETER ProfileName
Name of a profile entry in the JSON profile map to select (Mode 2).
.PARAMETER AdminUrl
SharePoint admin center URL (e.g. https://contoso-admin.sharepoint.com). Derived from -Tenant
when omitted.
.PARAMETER AppId
Application (client) ID of the Entra ID app registration used for certificate authentication.
.PARAMETER CertificateThumbprint
Thumbprint of the authentication certificate in Cert:\CurrentUser\My or Cert:\LocalMachine\My.
.PARAMETER CertificateMapPath
Path to the JSON profile map file. Defaults to o365-spo-admin-cert-auth.json under the
parent of the script directory (cert-export subfolder preferred).
.PARAMETER ProvisionEntraApp
With -GenerateLocalCertificate: also create the Entra app, upload the certificate, grant
permissions with admin consent, and update the profile map (requires Global Admin or
equivalent to consent).
.PARAMETER AppDisplayName
Display name for the provisioned Entra app. Defaults to the certificate subject.
.PARAMETER SetupClientId
Client ID of a public client app used for the interactive device-code Graph sign-in during
provisioning. Defaults to the well-known Azure PowerShell public client.
.PARAMETER CopyDeviceCodeToClipboard
Opt-in: copy the device code to the clipboard. Disabled by default because clipboard contents
can leak on shared/RDP sessions.
.EXAMPLE
.\o365-connect-spo-cert.ps1 -GenerateLocalCertificate -ProvisionEntraApp -Tenant contoso.onmicrosoft.com
One-time setup: creates the certificate, the Entra app, grants permissions, and saves a profile.
.EXAMPLE
.\o365-connect-spo-cert.ps1 -UseCertificateAuth
Connects using the single profile stored in the JSON profile map (prompts if several match).
.EXAMPLE
.\o365-connect-spo-cert.ps1 -UseCertificateAuth -Tenant contoso.onmicrosoft.com -AppId <guid> -CertificateThumbprint <thumb> -noprompt
Fully explicit, non-interactive connection suitable for scheduled automation.
.NOTES
Script provided as is. Use at own risk. No guarantees or warranty provided.
#>
[CmdletBinding()] ## FIX #15: enables -Debug and -Verbose switches at script level
param(
[switch]$noprompt = $false, ## if -noprompt used then user will not be asked for any input
[switch]$noupdate = $false, ## if -noupdate used then module will not be checked for more recent version
[switch]$enableLog = $false, ## if -enableLog create a transcript log file
[switch]$GenerateLocalCertificate = $false,
[switch]$UseCertificateAuth = $false,
[string]$GeneratedCertSubject = "O365-SPO-AppAuth",
[int]$GeneratedCertYearsValid = 2,
[string]$GeneratedCertOutputPath = "", ## defaults to parent of script directory at runtime
[switch]$ExportGeneratedPfx = $false,
[securestring]$GeneratedPfxPassword,
[string]$Tenant,
[string]$ProfileName,
[string]$AdminUrl, ## SharePoint admin center URL (e.g. https://contoso-admin.sharepoint.com)
[string]$AppId,
[string]$CertificateThumbprint,
[string]$CertificateMapPath = "", ## defaults to o365-spo-admin-cert-auth.json in parent of script directory
## When used with -GenerateLocalCertificate, also create the Entra app, upload the cert,
## grant Sites.FullControl.All, Graph Application.Read.All, Graph Group.Read.All,
## and update the profile map automatically.
[switch]$ProvisionEntraApp = $false,
[string]$AppDisplayName = "",
## Client ID of a public client app registered in your tenant for device-code Graph auth.
## Defaults to the well-known Azure PowerShell public client.
[string]$SetupClientId = "1950a258-227b-4e31-a9cf-717495945fc2",
## Opt-in only. Clipboard copy can leak auth codes in shared/RDP sessions.
[switch]$CopyDeviceCodeToClipboard = $false
)
<# CIAOPS
Script provided as is. Use at own risk. No guarantees or warranty provided.
Description - Simplified SharePoint Online admin center connect script with two modes:
1. GenerateLocalCertificate: create/export local cert files.
2. UseCertificateAuth: connect to SharePoint admin center with existing app/cert.
Usage - For setup and execution examples, see:
https://github.com/directorcia/Office365/wiki/Certificate-based-authentication-for-SharePoint-Online
Source - https://github.com/directorcia/Office365/blob/master/o365-connect-spo-cert.ps1
Documentation - https://github.com/directorcia/Office365/wiki/Certificate-based-authentication-for-SharePoint-Online
#>
## Resolve paths relative to the script file itself, not the caller's working directory.
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$scriptParentDir = Split-Path -Parent $scriptDir
if ([string]::IsNullOrWhiteSpace($GeneratedCertOutputPath)) { $GeneratedCertOutputPath = $scriptParentDir }
if ([string]::IsNullOrWhiteSpace($CertificateMapPath)) {
## Parent directory is searched first so reads are consistent with where writes land.
$candidateCertificateMapPaths = @(
(Join-Path $scriptParentDir 'cert-export/o365-spo-admin-cert-auth.json'),
(Join-Path $scriptParentDir 'o365-spo-admin-cert-auth.json'),
(Join-Path $scriptDir 'cert-export/o365-spo-admin-cert-auth.json'),
(Join-Path $scriptDir 'o365-spo-admin-cert-auth.json')
) | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }
foreach ($candidatePath in $candidateCertificateMapPaths) {
if (Test-Path -LiteralPath $candidatePath) {
$CertificateMapPath = $candidatePath
break
}
}
if ([string]::IsNullOrWhiteSpace($CertificateMapPath)) {
## Default write location: parent directory, matching GeneratedCertOutputPath convention.
$CertificateMapPath = Join-Path $scriptParentDir 'cert-export/o365-spo-admin-cert-auth.json'
}
}
## Shared output colors passed explicitly to functions to avoid hidden script-scope coupling.
$Colors = @{
SystemMessage = "cyan"
ProcessMessage = "green"
ErrorMessage = "red"
WarningMessage = "yellow"
}
## Well-known service principal app IDs used during provisioning.
$SpoResourceAppId = "00000003-0000-0ff1-ce00-000000000000"
$GraphResourceAppId = "00000003-0000-0000-c000-000000000000"
## Tracks whether this run opened a cert-auth SPO session that should be closed on error.
$disconnectCertificateAuthOnError = $false
function Get-ObjectPropertyValue {
<#
.SYNOPSIS
Read a note property without throwing under StrictMode when the JSON/object field is missing.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)][object]$InputObject,
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$Name,
[Parameter(Mandatory = $false)][object]$Default = $null
)
if ($null -eq $InputObject) {
return $Default
}
$property = $InputObject.PSObject.Properties[$Name]
if ($null -eq $property) {
return $Default
}
return $property.Value
}
## Resolve the executable of the current host so elevated module installs target the same runtime
## (PS5 vs PS7) and module path as the running script.
$elevatedShellPath = (Get-Process -Id $PID).MainModule.FileName
if ([string]::IsNullOrWhiteSpace($elevatedShellPath) -or -not (Test-Path -LiteralPath $elevatedShellPath)) {
throw "Unable to resolve current PowerShell host executable path for elevated module operations (PID $PID)."
}
function Resolve-SpoAdminCertificateProfile {
<#
.SYNOPSIS
Load and filter the JSON certificate profile map, returning the matching profile entry.
.OUTPUTS
PSCustomObject The selected profile entry, or $null if the map file is absent.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)][string]$Path,
[Parameter(Mandatory = $false)][string]$TenantFilter,
[Parameter(Mandatory = $false)][string]$ProfileFilter,
[Parameter(Mandatory = $false)][string]$AdminUrlFilter,
[Parameter(Mandatory = $false)][switch]$NoPrompt,
[Parameter(Mandatory = $true)][hashtable]$Colors
)
Write-Debug "Resolving certificate profile from map path: $Path"
if ([string]::IsNullOrWhiteSpace($Path) -or -not (Test-Path -Path $Path)) {
Write-Debug "Certificate map file missing or not provided."
return $null
}
try {
$raw = Get-Content -Path $Path -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
}
catch {
throw "Unable to parse certificate mapping file '$Path'. $($_.Exception.Message)"
}
$profileItems = @()
if ($raw -is [System.Array]) {
$profileItems = @($raw)
}
else {
$mappedProfiles = Get-ObjectPropertyValue $raw 'profiles'
if ($null -ne $mappedProfiles) {
$profileItems = @($mappedProfiles)
}
}
if ($profileItems.Count -eq 0) {
throw "No profiles found in certificate mapping file '$Path'."
}
$candidateProfiles = $profileItems
if (-not [string]::IsNullOrWhiteSpace($ProfileFilter)) {
$candidateProfiles = @($candidateProfiles | Where-Object { (Get-ObjectPropertyValue $_ 'name') -eq $ProfileFilter })
}
if (-not [string]::IsNullOrWhiteSpace($TenantFilter)) {
$candidateProfiles = @($candidateProfiles | Where-Object { (Get-ObjectPropertyValue $_ 'tenant') -eq $TenantFilter })
}
if (-not [string]::IsNullOrWhiteSpace($AdminUrlFilter)) {
$candidateProfiles = @($candidateProfiles | Where-Object { (Get-ObjectPropertyValue $_ 'adminUrl') -eq $AdminUrlFilter })
}
if ($candidateProfiles.Count -eq 0) {
$appliedFilters = @()
if (-not [string]::IsNullOrWhiteSpace($ProfileFilter)) { $appliedFilters += "ProfileName='$ProfileFilter'" }
if (-not [string]::IsNullOrWhiteSpace($TenantFilter)) { $appliedFilters += "Tenant='$TenantFilter'" }
if (-not [string]::IsNullOrWhiteSpace($AdminUrlFilter)) { $appliedFilters += "AdminUrl='$AdminUrlFilter'" }
$filterDesc = if ($appliedFilters.Count -gt 0) { " (filters: $($appliedFilters -join ', '))" } else { " (no filters applied)" }
$availableDesc = ($profileItems | ForEach-Object {
"name='$(Get-ObjectPropertyValue $_ 'name')' tenant='$(Get-ObjectPropertyValue $_ 'tenant')' adminUrl='$(Get-ObjectPropertyValue $_ 'adminUrl')'"
}) -join '; '
throw "No matching certificate profile found in '$Path'$filterDesc. Available profiles: [$availableDesc]"
}
if ($candidateProfiles.Count -eq 1 -or $NoPrompt) {
if ($candidateProfiles.Count -gt 1 -and $NoPrompt) {
throw "Multiple matching profiles found in '$Path'. Specify -ProfileName, -Tenant, or -AdminUrl."
}
return $candidateProfiles[0]
}
Write-Host -ForegroundColor $Colors.ProcessMessage "Multiple matching certificate profiles found:"
for ($index = 0; $index -lt $candidateProfiles.Count; $index++) {
$profileName = [string](Get-ObjectPropertyValue $candidateProfiles[$index] 'name')
$displayName = if ([string]::IsNullOrWhiteSpace($profileName)) { "(unnamed)" } else { $profileName }
Write-Host -ForegroundColor $Colors.ProcessMessage ("[{0}] {1} | Tenant={2} | AdminUrl={3} | AppId={4}" -f ($index + 1), $displayName, (Get-ObjectPropertyValue $candidateProfiles[$index] 'tenant'), (Get-ObjectPropertyValue $candidateProfiles[$index] 'adminUrl'), (Get-ObjectPropertyValue $candidateProfiles[$index] 'appId'))
}
do {
$choice = Read-Host -Prompt "Select profile number"
[int]$parsedChoice = 0
$validSelection = [int]::TryParse($choice, [ref]$parsedChoice) -and $parsedChoice -ge 1 -and $parsedChoice -le $candidateProfiles.Count
} until ($validSelection)
return $candidateProfiles[$parsedChoice - 1]
}
function Resolve-SpoAdminCertificate {
<#
.SYNOPSIS
Resolve a certificate from the current user or local machine personal store by thumbprint.
If the private-key certificate is not yet present in the store, this will attempt to import
it from a previously exported PFX file.
.OUTPUTS
X509Certificate2 The resolved certificate object.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$Thumbprint,
[Parameter(Mandatory = $true)][hashtable]$Colors,
[Parameter(Mandatory = $false)][string[]]$CandidatePfxPaths = @()
)
if ([string]::IsNullOrWhiteSpace($Thumbprint)) {
throw "Certificate thumbprint was empty."
}
$normalizedThumbprint = ($Thumbprint -replace '\s', '').ToUpperInvariant()
$storePaths = @(
'Cert:\CurrentUser\My',
'Cert:\LocalMachine\My'
)
foreach ($storePath in $storePaths) {
Write-Debug "Searching certificate store '$storePath' for thumbprint '$Thumbprint'."
$matchingCert = Get-ChildItem -Path $storePath -ErrorAction SilentlyContinue |
Where-Object {
$_.Thumbprint -and
((($_.Thumbprint) -replace '\s', '').ToUpperInvariant()) -eq $normalizedThumbprint
} |
Select-Object -First 1
if ($null -ne $matchingCert) {
if (-not $matchingCert.HasPrivateKey) {
throw "Certificate '$Thumbprint' was found but does not expose a private key. Import the matching PFX or ensure the certificate was created with a private key."
}
Write-Debug "Resolved certificate '$Thumbprint' from $storePath."
return $matchingCert
}
}
## Cert not in either store - fall back to searching for a previously exported PFX file.
## A PFX is only considered a match if its file name contains the requested thumbprint
## (the export naming convention is <subject>-<thumbprint>.pfx), and import is attempted
## with an empty password only, matching the script's own no-password export default.
$pfxSearchRoots = @(
$script:scriptDir,
$script:scriptParentDir,
$env:TEMP,
$PWD.Path
) + @($CandidatePfxPaths | Where-Object { -not [string]::IsNullOrWhiteSpace($_) })
foreach ($searchRoot in ($pfxSearchRoots | Select-Object -Unique)) {
if ([string]::IsNullOrWhiteSpace($searchRoot) -or -not (Test-Path -LiteralPath $searchRoot)) {
continue
}
$candidatePfxs = @()
if ((Test-Path -LiteralPath $searchRoot) -and (Get-Item -LiteralPath $searchRoot -ErrorAction SilentlyContinue).PSIsContainer) {
$candidatePfxs = @(Get-ChildItem -Path $searchRoot -Filter '*.pfx' -File -Recurse -ErrorAction SilentlyContinue)
}
elseif ($searchRoot -like '*.pfx') {
$candidatePfxs = @(Get-Item -LiteralPath $searchRoot -ErrorAction SilentlyContinue)
}
foreach ($candidatePfx in $candidatePfxs) {
$candidateName = $candidatePfx.Name
if ($candidateName -notmatch [regex]::Escape($normalizedThumbprint) -and $candidateName -notmatch [regex]::Escape(($Thumbprint -replace '\s', ''))) {
continue
}
try {
Write-Host -ForegroundColor $Colors.ProcessMessage "Importing certificate from PFX: $($candidatePfx.FullName)"
$emptyPassword = [System.Security.SecureString]::new()
$importedCert = Import-PfxCertificate -FilePath $candidatePfx.FullName -CertStoreLocation 'Cert:\CurrentUser\My' -Password $emptyPassword -Exportable -ErrorAction Stop
if ($null -ne $importedCert) {
if (-not $importedCert.HasPrivateKey) {
throw "Imported certificate '$Thumbprint' does not expose a private key."
}
Write-Debug "Resolved certificate '$Thumbprint' from imported PFX $($candidatePfx.FullName)."
return $importedCert
}
}
catch {
Write-Debug "Unable to import certificate from PFX '$($candidatePfx.FullName)': $($_.Exception.Message)"
}
}
}
throw "Certificate with thumbprint '$Thumbprint' was not found in Cert:\CurrentUser\My or Cert:\LocalMachine\My and no importable PFX was found. Import the matching PFX or run -GenerateLocalCertificate on this machine first."
}
function Resolve-SpoAdminCertificateThumbprint {
<#
.SYNOPSIS
Find a suitable local certificate thumbprint when one was not explicitly supplied.
.OUTPUTS
String The resolved thumbprint or $null if no suitable certificate was found.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)][string]$PreferredSubject = "",
[Parameter(Mandatory = $true)][hashtable]$Colors
)
$candidateSubjects = @()
if (-not [string]::IsNullOrWhiteSpace($PreferredSubject)) {
$candidateSubjects += $PreferredSubject
$candidateSubjects += "CN=$PreferredSubject"
$candidateSubjects += "O365-SPO-AppAuth"
}
else {
$candidateSubjects += "O365-SPO-AppAuth"
}
$storePaths = @('Cert:\CurrentUser\My', 'Cert:\LocalMachine\My')
foreach ($storePath in $storePaths) {
## FIX #2: Force array with @() so .Count is reliable when Get-ChildItem returns a single object (PS5.1).
$matchingCerts = @(Get-ChildItem -Path $storePath -ErrorAction SilentlyContinue |
Where-Object { $_.HasPrivateKey -and $_.Thumbprint })
if ($matchingCerts.Count -gt 0) {
$preferredMatches = @($matchingCerts | Where-Object {
$subjectText = [string]$_.Subject
$friendlyName = [string]$_.FriendlyName
foreach ($subject in $candidateSubjects) {
if ($subjectText -like "*$subject*" -or $friendlyName -like "*$subject*") {
return $true
}
}
return $false
})
if ($preferredMatches.Count -gt 0) {
$selectedCert = $preferredMatches | Sort-Object NotAfter -Descending | Select-Object -First 1
return $selectedCert.Thumbprint
}
}
}
return $null
}
function New-SpoAdminLocalCertificate {
<#
.SYNOPSIS
Generate a self-signed RSA-2048 certificate for SharePoint Online admin app authentication.
.OUTPUTS
PSCustomObject Certificate metadata and paths to the exported .cer and optional .pfx.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$SubjectName,
[Parameter(Mandatory = $true)]
[ValidateRange(1, 100)]
[int]$YearsValid,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$OutputPath,
[Parameter(Mandatory = $false)]
[switch]$ExportPfx,
[Parameter(Mandatory = $false)]
[securestring]$PfxPassword,
[Parameter(Mandatory = $false)]
[switch]$NoPrompt,
[Parameter(Mandatory = $false)]
[string]$FriendlyName = ""
)
Write-Debug "Starting local certificate generation."
if (-not (Test-Path -Path $OutputPath)) {
Write-Debug "Creating certificate output directory: $OutputPath"
New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null
}
$certificate = New-SelfSignedCertificate -Subject "CN=$SubjectName" -CertStoreLocation "Cert:\CurrentUser\My" -KeyAlgorithm RSA -KeyLength 2048 -HashAlgorithm SHA256 -KeyExportPolicy Exportable -NotAfter (Get-Date).AddYears($YearsValid) -KeySpec Signature -ErrorAction Stop
## FIX #5: FriendlyName is Windows-only; guard against failure on PS7/Linux/macOS.
$resolvedFriendlyName = if ([string]::IsNullOrWhiteSpace($FriendlyName)) { $SubjectName } else { $FriendlyName }
try {
$certificate.FriendlyName = $resolvedFriendlyName
Write-Debug "Certificate friendly name set to: $resolvedFriendlyName"
}
catch {
Write-Debug "Could not set FriendlyName (non-Windows platform or restricted store): $($_.Exception.Message)"
}
$safeSubject = ($SubjectName -replace '[^A-Za-z0-9\-_.]', '-')
$fileBase = "{0}-{1}" -f $safeSubject, $certificate.Thumbprint
$cerPath = Join-Path -Path $OutputPath -ChildPath "$fileBase.cer"
Export-Certificate -Cert $certificate -FilePath $cerPath -Type CERT -Force -ErrorAction Stop | Out-Null
$pfxPath = ""
if ($ExportPfx) {
$securePfxPassword = $PfxPassword
if ($null -eq $securePfxPassword -and -not $NoPrompt) {
$securePfxPassword = Read-Host -Prompt "Enter password for generated PFX file" -AsSecureString
}
if ($null -eq $securePfxPassword) {
Write-Debug "No explicit PFX password supplied; using an empty password for local import compatibility."
## FIX #9: Warn prominently that an unprotected PFX is being written to disk.
Write-Host -ForegroundColor "yellow" "WARNING: PFX will be exported with an EMPTY password. The private key is unprotected on disk. Secure or delete the PFX file after import."
$securePfxPassword = [System.Security.SecureString]::new()
}
$pfxPath = Join-Path -Path $OutputPath -ChildPath "$fileBase.pfx"
Export-PfxCertificate -Cert $certificate -FilePath $pfxPath -Password $securePfxPassword -Force -ErrorAction Stop | Out-Null
}
return [PSCustomObject]@{
Thumbprint = $certificate.Thumbprint
Subject = $certificate.Subject
NotAfter = $certificate.NotAfter
CerPath = $cerPath
PfxPath = $pfxPath ## empty string when not exported, for safe JSON serialisation
}
}
function Get-DeviceCodeGraphToken {
<#
.SYNOPSIS
Authenticate to Microsoft Graph using the device-code OAuth2 flow.
.OUTPUTS
String Raw OAuth2 access token string suitable for use in Authorization headers.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$TenantId,
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$ClientId,
[Parameter(Mandatory = $false)][string]$Scope = "https://graph.microsoft.com/Application.ReadWrite.All https://graph.microsoft.com/AppRoleAssignment.ReadWrite.All",
[Parameter(Mandatory = $false)][switch]$CopyCodeToClipboard,
[Parameter(Mandatory = $true)][hashtable]$Colors
)
Write-Debug "Requesting device code for tenant: $TenantId, client: $ClientId"
try {
$deviceCodeResponse = Invoke-RestMethod -Method Post `
-Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/devicecode" `
-Body @{ client_id = $ClientId; scope = $Scope } `
-ContentType "application/x-www-form-urlencoded" `
-ErrorAction Stop
}
catch {
throw "Device code request failed. Check -SetupClientId and -Tenant. Error: $($_.Exception.Message)"
}
if ($CopyCodeToClipboard) {
## Clipboard copy is opt-in only to reduce exposure on shared/RDP sessions.
Set-Clipboard -Value $deviceCodeResponse.user_code
}
Write-Host -ForegroundColor $Colors.SystemMessage "`n--- Graph Authentication Required ---"
Write-Host -ForegroundColor $Colors.SystemMessage "Opening browser: $($deviceCodeResponse.verification_uri)"
if ($CopyCodeToClipboard) {
Write-Host -ForegroundColor $Colors.SystemMessage "Device code (copied to clipboard): $($deviceCodeResponse.user_code)"
}
else {
Write-Host -ForegroundColor $Colors.SystemMessage "Device code: $($deviceCodeResponse.user_code)"
Write-Host -ForegroundColor $Colors.WarningMessage "Clipboard copy is disabled by default for security on shared/RDP sessions. Use -CopyDeviceCodeToClipboard to enable it."
}
Write-Host -ForegroundColor $Colors.SystemMessage "Paste the code in the browser and sign in, then return here."
Write-Host -ForegroundColor $Colors.SystemMessage "-------------------------------------`n"
## Browser launch is best-effort; on headless/remote sessions the user can browse from another device.
try {
Start-Process $deviceCodeResponse.verification_uri -ErrorAction Stop
}
catch {
Write-Host -ForegroundColor $Colors.WarningMessage "Could not open a browser automatically. Browse to $($deviceCodeResponse.verification_uri) manually."
}
$tokenBody = @{
grant_type = "urn:ietf:params:oauth:grant-type:device_code"
client_id = $ClientId
device_code = $deviceCodeResponse.device_code
}
$deadline = (Get-Date).AddSeconds($deviceCodeResponse.expires_in)
## FIX #7: Explicitly cast to [int] to avoid type-widening from JSON long on PS7.
$pollInterval = [int]$deviceCodeResponse.interval
## Poll the token endpoint per RFC 8628 until the user completes browser sign-in:
## - 'authorization_pending' -> keep polling at the server-suggested interval
## - 'slow_down' -> back off by 5 seconds and keep polling
## - any other error, or reaching the device-code expiry deadline -> abort
:pollLoop while ((Get-Date) -lt $deadline) {
Start-Sleep -Seconds $pollInterval
try {
$tokenResponse = Invoke-RestMethod -Method Post `
-Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" `
-Body $tokenBody `
-ContentType "application/x-www-form-urlencoded" `
-ErrorAction Stop
Write-Debug "Graph token acquired."
return $tokenResponse.access_token
}
catch {
$errorContent = $null
try { $errorContent = ($_.ErrorDetails.Message | ConvertFrom-Json) } catch {}
if ($null -ne $errorContent) {
switch ($errorContent.error) {
"authorization_pending" {
Write-Debug "Waiting for user to complete sign-in..."
continue pollLoop
}
"slow_down" {
$pollInterval += 5
continue pollLoop
}
"authorization_declined" { throw "User declined the authorization request." }
"expired_token" { throw "Device code expired before authorization was completed." }
default { throw "Token exchange failed ($($errorContent.error)): $($errorContent.error_description)" }
}
}
throw "Token exchange failed: $($_.Exception.Message)"
}
}
throw "Device code authorization timed out."
}
function Invoke-SpoAdminGraphRequest {
<#
.SYNOPSIS
Helper: make an authenticated Graph REST call and return the parsed response.
.OUTPUTS
PSObject The parsed JSON response body returned by Microsoft Graph.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$AccessToken,
[Parameter(Mandatory = $true)][ValidateSet('Get', 'Post', 'Patch', 'Put', 'Delete')][string]$Method,
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$Uri,
[Parameter(Mandatory = $false)][object]$Body,
[Parameter(Mandatory = $false)][ValidateRange(0, 10)][int]$MaxRetries = 5,
[Parameter(Mandatory = $false)][ValidateRange(1, 60)][int]$InitialRetryDelaySeconds = 2
)
$headers = @{ Authorization = "Bearer $AccessToken"; "Content-Type" = "application/json" }
$params = @{ Method = $Method; Uri = $Uri; Headers = $headers; ErrorAction = "Stop" }
if ($null -ne $Body) {
$params.Body = ($Body | ConvertTo-Json -Depth 10 -Compress)
}
$attempt = 0
while ($true) {
try {
return Invoke-RestMethod @params
}
catch {
$attempt++
$detail = $null
try { $detail = ($_.ErrorDetails.Message | ConvertFrom-Json).error.message } catch {}
$msg = if ($null -ne $detail) { $detail } else { $_.Exception.Message }
$statusCode = $null
$retryAfterSeconds = $null
$response = $null
try { $response = $_.Exception.Response } catch {}
if ($null -ne $response) {
try { $statusCode = [int]$response.StatusCode } catch {}
try {
## FIX #4: Normalise Retry-After header access for PS5.1 (WebHeaderCollection) and PS7 (IEnumerable<string>).
$retryAfterRaw = $null
try {
## PS7: HttpResponseMessage.Headers is a typed collection; use GetValues() if available.
$retryAfterRaw = $response.Headers.GetValues('Retry-After') | Select-Object -First 1
}
catch {
## PS5.1: WebHeaderCollection supports string indexing directly.
try { $retryAfterRaw = [string]$response.Headers['Retry-After'] } catch {}
}
if (-not [string]::IsNullOrWhiteSpace($retryAfterRaw)) {
[int]$parsedRetryAfter = 0
if ([int]::TryParse($retryAfterRaw.Trim(), [ref]$parsedRetryAfter) -and $parsedRetryAfter -gt 0) {
$retryAfterSeconds = $parsedRetryAfter
}
}
}
catch {}
}
## Retry only transient failures: HTTP 429 (throttling) and 5xx (server errors), or
## throttling-flavoured messages when no status code is available. A Retry-After header,
## when present, overrides the exponential backoff (2s, 4s, 8s, ... capped at 30s).
$isRetriableStatus = ($statusCode -in @(429, 500, 502, 503, 504))
$isRetriableMessage = ($msg -match '(?i)too many requests|throttl|rate limit|temporar|timeout|try again')
$shouldRetry = ($attempt -le $MaxRetries) -and ($isRetriableStatus -or $isRetriableMessage)
if (-not $shouldRetry) {
throw "Graph call failed [$Method $Uri]: $msg"
}
$backoffSeconds = [math]::Pow(2, ($attempt - 1)) * $InitialRetryDelaySeconds
$delaySeconds = if ($null -ne $retryAfterSeconds -and $retryAfterSeconds -gt 0) { [int]$retryAfterSeconds } else { [int][math]::Min(30, $backoffSeconds) }
Write-Debug "Graph call retry $attempt/$MaxRetries after ${delaySeconds}s for [$Method $Uri]. Status=$statusCode"
Start-Sleep -Seconds $delaySeconds
}
}
}
function Set-SpoAdminProfileMapEntry {
<#
.SYNOPSIS
Atomically upsert a certificate profile entry in the JSON profile map file.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$MapPath,
[Parameter(Mandatory = $true)][object]$ProfileEntry,
[Parameter(Mandatory = $true)][hashtable]$Colors
)
$fullMapPath = [System.IO.Path]::GetFullPath($MapPath)
## FIX #11: Dispose SHA256 instance properly to avoid unmanaged resource leak.
$sha256 = [System.Security.Cryptography.SHA256]::Create()
$hashBytes = $null
try {
$hashBytes = $sha256.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($fullMapPath.ToLowerInvariant()))
}
finally {
$sha256.Dispose()
}
## A system-wide named mutex (name derived from the map file path) serialises writes so
## concurrent script runs against the same JSON file cannot corrupt it. The write itself is
## atomic: content goes to a temp file first, then Move-Item replaces the real file.
$hashHex = ([System.BitConverter]::ToString($hashBytes)).Replace('-', '')
$mutexName = "Global\CIAOPS_SPO_ADMIN_PROFILEMAP_$hashHex"
$mutex = New-Object System.Threading.Mutex($false, $mutexName)
$hasHandle = $false
$tempPath = "$fullMapPath.$PID.tmp"
try {
try {
$hasHandle = $mutex.WaitOne([TimeSpan]::FromSeconds(30))
}
catch [System.Threading.AbandonedMutexException] {
$hasHandle = $true
Write-Debug "Profile map mutex was abandoned by a previous run; continuing with recovered lock ownership."
}
if (-not $hasHandle) {
throw "Timed out waiting for profile map lock: $fullMapPath"
}
Write-Verbose "Profile map lock acquired for: $fullMapPath"
## FIX #19: Ensure the map directory exists - the default path lives under cert-export/ which may not exist yet.
$mapDir = Split-Path -Parent $fullMapPath
if (-not [string]::IsNullOrWhiteSpace($mapDir) -and -not (Test-Path -LiteralPath $mapDir)) {
New-Item -Path $mapDir -ItemType Directory -Force | Out-Null
}
$mapData = @{ profiles = @() }
if (Test-Path -Path $fullMapPath) {
try {
$raw = Get-Content -Path $fullMapPath -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
$existingProfiles = Get-ObjectPropertyValue $raw 'profiles'
if ($null -ne $existingProfiles) { $mapData = @{ profiles = @($existingProfiles) } }
elseif ($raw -is [System.Array]) { $mapData = @{ profiles = @($raw) } }
}
catch {
Write-Debug "Could not parse existing profile map inside lock - will overwrite."
}
}
$profileList = [System.Collections.Generic.List[object]]::new()
foreach ($p in @($mapData.profiles)) { $profileList.Add($p) }
## Replace existing entry for the same tenant or appId, or append.
$existingIdx = $null
$entryAppId = [string](Get-ObjectPropertyValue $ProfileEntry 'appId')
$entryTenant = [string](Get-ObjectPropertyValue $ProfileEntry 'tenant')
for ($i = 0; $i -lt $profileList.Count; $i++) {
$existingAppId = [string](Get-ObjectPropertyValue $profileList[$i] 'appId')
$existingTenant = [string](Get-ObjectPropertyValue $profileList[$i] 'tenant')
$sameApp = (-not [string]::IsNullOrWhiteSpace($existingAppId) -and $existingAppId -eq $entryAppId)
$sameTenant = (-not [string]::IsNullOrWhiteSpace($existingTenant) -and $existingTenant -eq $entryTenant)
if ($sameApp -or $sameTenant) { $existingIdx = $i; break }
}
if ($null -ne $existingIdx) { $profileList[$existingIdx] = $ProfileEntry } else { $profileList.Add($ProfileEntry) }
@{ profiles = $profileList.ToArray() } | ConvertTo-Json -Depth 5 | Set-Content -Path $tempPath -Encoding UTF8
Move-Item -Path $tempPath -Destination $fullMapPath -Force
Write-Host -ForegroundColor $Colors.ProcessMessage "Profile map updated: $fullMapPath"
}
finally {
if (Test-Path -Path $tempPath) {
Remove-Item -Path $tempPath -Force -ErrorAction SilentlyContinue
}
if ($hasHandle) {
$mutex.ReleaseMutex()
}
$mutex.Dispose()
}
}
function Get-CertClientAssertionToken {
<#
.SYNOPSIS
Acquire a Graph access token using a JWT client assertion signed with a local certificate.
No user interaction required - uses the OAuth2 client_credentials flow.
.OUTPUTS
String Raw OAuth2 access token string.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$TenantId,
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$AppId,
[Parameter(Mandatory = $true)][System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,
[string]$Scope = "https://graph.microsoft.com/.default"
)
## The client_credentials flow with a certificate works by sending a short-lived, self-signed
## JWT ("client assertion") instead of a client secret. The JWT has three base64url parts:
## header (alg + cert thumbprint), payload (issuer/audience/expiry claims), and an RSA-SHA256
## signature produced with the certificate's private key. Entra ID validates the signature
## against the public key uploaded to the app registration.
## Build the x5t (base64url of cert SHA-1 thumbprint bytes) for the JWT header.
$thumbprintBytes = $Certificate.GetCertHash()
$x5t = [System.Convert]::ToBase64String($thumbprintBytes).TrimEnd('=').Replace('+', '-').Replace('/', '_')
$tokenEndpoint = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token"
## [DateTimeOffset]::UtcNow.ToUnixTimeSeconds() is portable across PS5.1 and PS7.
$now = [int][DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
## JWT header and payload - both must be base64url encoded.
$headerJson = '{"alg":"RS256","typ":"JWT","x5t":"' + $x5t + '"}'
$payloadJson = '{"aud":"' + $tokenEndpoint + '","iss":"' + $AppId + '","sub":"' + $AppId + '","jti":"' + [System.Guid]::NewGuid().ToString() + '","nbf":' + $now + ',"exp":' + ($now + 600) + '}'
$headerB64 = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($headerJson)).TrimEnd('=').Replace('+', '-').Replace('/', '_')
$payloadB64 = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($payloadJson)).TrimEnd('=').Replace('+', '-').Replace('/', '_')
$signingInput = [System.Text.Encoding]::UTF8.GetBytes("$headerB64.$payloadB64")
## Sign with the certificate's RSA private key using PKCS#1 v1.5 / SHA-256.
$rsa = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($Certificate)
if ($null -eq $rsa) {
throw "Certificate does not expose an RSA private key required for client assertion signing."
}
try {
$sigBytes = $rsa.SignData($signingInput, [System.Security.Cryptography.HashAlgorithmName]::SHA256, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1)
}
finally {
$rsa.Dispose()
}
$sigB64 = [System.Convert]::ToBase64String($sigBytes).TrimEnd('=').Replace('+', '-').Replace('/', '_')
$clientAssertion = "$headerB64.$payloadB64.$sigB64"
Write-Debug "Requesting Graph token via client assertion for app $AppId in tenant $TenantId"
try {
$response = Invoke-RestMethod -Method Post -Uri $tokenEndpoint -ErrorAction Stop `
-ContentType "application/x-www-form-urlencoded" `
-Body @{
grant_type = "client_credentials"
client_id = $AppId
scope = $Scope
client_assertion_type = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
client_assertion = $clientAssertion
}
return $response.access_token
}
catch {
$detail = $null
try { $detail = ($_.ErrorDetails.Message | ConvertFrom-Json).error_description } catch {}
throw "Client assertion token request failed: $(if ($detail) { $detail } else { $_.Exception.Message })"
}
}
function Write-SpoAdminCertConnectionDetails {
<#
.SYNOPSIS
Display local certificate details and the matching Entra ID app/keyCredential after connecting.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$TenantId,
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$AppId,
[Parameter(Mandatory = $true)][System.Security.Cryptography.X509Certificates.X509Certificate2]$LocalCert,
[Parameter(Mandatory = $true)][hashtable]$Colors
)
$sep = "-" * 60
Write-Host -ForegroundColor $Colors.ProcessMessage "`n$sep"
Write-Host -ForegroundColor $Colors.ProcessMessage " LOCAL CERTIFICATE"
Write-Host -ForegroundColor $Colors.ProcessMessage $sep
Write-Host -ForegroundColor $Colors.ProcessMessage (" Friendly Name : {0}" -f $(if ($LocalCert.FriendlyName) { $LocalCert.FriendlyName } else { "(none)" }))
Write-Host -ForegroundColor $Colors.ProcessMessage (" Subject : {0}" -f $LocalCert.Subject)
Write-Host -ForegroundColor $Colors.ProcessMessage (" Thumbprint : {0}" -f $LocalCert.Thumbprint)
Write-Host -ForegroundColor $Colors.ProcessMessage (" Issuer : {0}" -f $LocalCert.Issuer)
Write-Host -ForegroundColor $Colors.ProcessMessage (" Valid From : {0}" -f $LocalCert.NotBefore.ToString('yyyy-MM-dd HH:mm:ss'))
Write-Host -ForegroundColor $Colors.ProcessMessage (" Valid To : {0}" -f $LocalCert.NotAfter.ToString('yyyy-MM-dd HH:mm:ss'))
## Attempt to fetch Entra app details using a client assertion (no user interaction).
$graphToken = $null
try {
$graphToken = Get-CertClientAssertionToken -TenantId $TenantId -AppId $AppId -Certificate $LocalCert
$graphBase = "https://graph.microsoft.com/v1.0"
$appFilter = [uri]::EscapeDataString("appId eq '" + ($AppId -replace "'", "''") + "'")
$appResult = Invoke-SpoAdminGraphRequest -AccessToken $graphToken -Method Get `
-Uri "$graphBase/applications?`$filter=$appFilter&`$select=displayName,keyCredentials"
$appObj = $appResult.value | Select-Object -First 1
Write-Host -ForegroundColor $Colors.ProcessMessage "`n$sep"
Write-Host -ForegroundColor $Colors.ProcessMessage " ENTRA ID APP REGISTRATION"
Write-Host -ForegroundColor $Colors.ProcessMessage $sep
Write-Host -ForegroundColor $Colors.ProcessMessage (" Display Name : {0}" -f $appObj.displayName)
Write-Host -ForegroundColor $Colors.ProcessMessage (" App ID : {0}" -f $AppId)
## Find the keyCredential whose customKeyIdentifier matches this cert's SHA-1 thumbprint.
$thumbBase64 = [System.Convert]::ToBase64String($LocalCert.GetCertHash())
$matchingKey = $appObj.keyCredentials | Where-Object { $_.customKeyIdentifier -eq $thumbBase64 } | Select-Object -First 1
if ($null -ne $matchingKey) {
Write-Host -ForegroundColor $Colors.ProcessMessage (" Cert Label : {0}" -f $matchingKey.displayName)
Write-Host -ForegroundColor $Colors.ProcessMessage (" Cert Start : {0}" -f ([datetime]$matchingKey.startDateTime).ToString('yyyy-MM-dd HH:mm:ss'))
Write-Host -ForegroundColor $Colors.ProcessMessage (" Cert End : {0}" -f ([datetime]$matchingKey.endDateTime).ToString('yyyy-MM-dd HH:mm:ss'))
}
else {
Write-Host -ForegroundColor $Colors.WarningMessage " Matching key credential not found in Entra app (thumbprint mismatch or cert not yet uploaded)."
}
## Show all other certs registered on the same app.
$otherKeys = @($appObj.keyCredentials | Where-Object { $_.customKeyIdentifier -ne $thumbBase64 })
if ($otherKeys.Count -gt 0) {
Write-Host -ForegroundColor $Colors.ProcessMessage ("`n Other registered certs on this app ({0}):" -f $otherKeys.Count)
foreach ($key in $otherKeys) {
Write-Host -ForegroundColor $Colors.ProcessMessage (" - {0} [{1} -> {2}]" -f $key.displayName, ([datetime]$key.startDateTime).ToString('yyyy-MM-dd'), ([datetime]$key.endDateTime).ToString('yyyy-MM-dd'))
}
}
}
catch {
$entraDetailError = $_.Exception.Message
if ($entraDetailError -match "Insufficient privileges") {
Write-Host -ForegroundColor $Colors.WarningMessage "`n Entra ID cert details skipped: this app lacks Graph read permission for applications."
Write-Host -ForegroundColor $Colors.WarningMessage " Local cert details above are valid; SPO connection is unaffected."
Write-Host -ForegroundColor $Colors.WarningMessage " To enable Entra matching details, grant Microsoft Graph Application.Read.All (Application) and admin consent."
}
else {
Write-Host -ForegroundColor $Colors.WarningMessage "`n (Entra ID cert details unavailable: $entraDetailError)"
}
}
finally {
if ($null -ne $graphToken) {
Remove-Variable -Name graphToken -ErrorAction SilentlyContinue
}
}
Write-Host -ForegroundColor $Colors.ProcessMessage "$sep`n"
}
function Get-SpoAdminProvisioningRoleTargets {
<#
.SYNOPSIS
Resolve the SharePoint Online and Microsoft Graph service principals and required app role IDs.
.OUTPUTS
PSCustomObject SpoServicePrincipal, SpoSitesFullRole, GraphServicePrincipal,
GraphReadAllRole, GraphGroupReadAllRole.
#>
[CmdletBinding()]