Private/Assert-NSPConditionalAccessSession.ps1
|
function Assert-NSPConditionalAccessSession { <# .SYNOPSIS Returns the current Graph context only if it is signed in as this tool's recorded app for that tenant, with every scope. Otherwise throws with the exact command to run. .DESCRIPTION A session from another app, such as the Graph SDK default app left over from Register-NSPConditionalAccessAppRegistration, is refused even if it happens to hold the scopes. Tenant work always runs as NSP-M365-ConditionalAccess. #> [CmdletBinding()] param( [string]$ConfigRoot ) if ($script:UnattendedCoverage) { # Set only by Invoke-NSPConditionalAccessCoverageJob for the length of the job: the # session must be the recorded coverage app, app-only, in the job's tenant. $context = Connect-NSPGraph -Scopes @(Get-NSPConditionalAccessGraphScopes -Purpose Coverage) -Optional if (-not $context -or [string]$context.AuthType -ne 'AppOnly' -or $context.ClientId -ne $script:UnattendedCoverage.ClientId -or $context.TenantId -ne $script:UnattendedCoverage.TenantId) { throw "The unattended session is not the coverage app $($script:UnattendedCoverage.ClientId) signed in app-only to tenant $($script:UnattendedCoverage.TenantId)." } return $context } $context = Connect-NSPGraph -Scopes @(Get-NSPConditionalAccessGraphScopes) -Optional if (-not $context) { throw "No Graph session. Run: Connect-NSPConditionalAccessGraph -Tenant '<tenant id or domain>'" } $recordPath = Join-Path (Get-NSPConditionalAccessLocalPath -Kind AppRegistrations -ConfigRoot $ConfigRoot) "$($context.TenantId).json" if (-not (Test-Path -LiteralPath $recordPath)) { throw "Tenant $($context.TenantId) has no recorded NSP-M365-ConditionalAccess registration. Run Register-NSPConditionalAccessAppRegistration -Execute there first." } $record = Get-Content -LiteralPath $recordPath -Raw | ConvertFrom-Json $tenantLabel = if ($record.TenantDomain) { $record.TenantDomain } else { $record.TenantId } $reconnect = "Run: Connect-NSPConditionalAccessGraph -Tenant '$tenantLabel'" if ($context.ClientId -ne $record.ClientId) { throw "The Graph session is signed in as app $($context.ClientId), not NSP-M365-ConditionalAccess ($($record.ClientId)). $reconnect" } $missing = @(Get-NSPConditionalAccessGraphScopes | Where-Object { $_ -notin @($context.Scopes) }) if ($missing.Count) { throw "The Graph session lacks $($missing -join ', '). $reconnect" } $context } |