Private/Remove-365TuneElevation.ps1
|
function Remove-365TuneElevation { <# .SYNOPSIS Removes User Access Administrator elevation from root scope for the current user. #> $ctx = Get-AzContext $currentUser = $ctx.Account.Id # For MSI/SP accounts SignInName is empty - match by ObjectId as fallback $currentOid = $ctx.Account.ExtendedProperties["HomeAccountId"] -replace "\..*","" if (-not $currentOid) { $currentOid = (Invoke-AzRestMethod -Path "/providers/Microsoft.Authorization/elevateAccess?api-version=2015-07-01" -Method GET -ErrorAction SilentlyContinue) } # Get token to find current user's OID try { $meToken = Get-AzAccessToken -ResourceUrl "https://graph.microsoft.com" -ErrorAction Stop $meTokenStr = if ($meToken.Token -is [System.Security.SecureString]) { [System.Net.NetworkCredential]::new("", $meToken.Token).Password } else { $meToken.Token } $jwtPayload = $meTokenStr.Split(".")[1] # Pad base64 $pad = 4 - ($jwtPayload.Length % 4); if ($pad -ne 4) { $jwtPayload += "=" * $pad } $claims = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($jwtPayload)) | ConvertFrom-Json $currentOid = $claims.oid } catch {} $assignment = Get-AzRoleAssignment -RoleDefinitionId "18d7d88d-d35e-4fb5-a5c3-7773c20a72d9" ` -ErrorAction SilentlyContinue | Where-Object { $_.Scope -eq "/" -and ($_.SignInName -eq $currentUser -or $_.ObjectId -eq $currentOid) } if (-not $assignment) { Write-Host " Elevation already removed." -ForegroundColor Gray return } # Wait for elevated token to propagate before DELETE Write-Host " Waiting for propagation..." -ForegroundColor Gray Start-Sleep -Seconds 20 $response = Invoke-AzRestMethod ` -Path "$($assignment.RoleAssignmentId)?api-version=2018-07-01" ` -Method DELETE if ($response.StatusCode -in @(200, 204)) { Write-Host " [OK] Elevation removed." -ForegroundColor Green } elseif ($response.StatusCode -eq 403) { # Retry once after additional propagation delay Write-Host " Retrying after additional propagation delay..." -ForegroundColor Gray Start-Sleep -Seconds 20 $null = Get-AzAccessToken -ResourceUrl "https://management.azure.com" -ErrorAction SilentlyContinue $retry = Invoke-AzRestMethod -Path "$($assignment.RoleAssignmentId)?api-version=2018-07-01" -Method DELETE if ($retry.StatusCode -in @(200, 204)) { Write-Host " [OK] Elevation removed." -ForegroundColor Green } else { Write-Warning " [WARN] Elevation removal returned status $($retry.StatusCode) -- remove manually: Azure Portal > Properties > Access management for Azure resources." } } else { Write-Warning " [WARN] Elevation removal returned status $($response.StatusCode) -- remove manually: Azure Portal > Properties > Access management for Azure resources." } } |