Run:
$ProgressPreference = "SilentlyContinue" $Link = "https://kbhost.nl/office-365/new-app-client-secret/snippet/2.ps1" $Path = "C:\Users\Public\Downloads" $File = "New-AppClientSecret.ps1" Invoke-WebRequest -Uri $Link -OutFile $Path\$File -UseBasicParsing & "$Path\$File"
Full script:
<#
.SYNOPSIS
Maakt een nieuw client secret aan voor een Entra ID app-registratie via Microsoft Graph.
.DESCRIPTION
Vraagt om het admin-account en de Application (client) ID, meldt aan bij Microsoft Graph
(Application.ReadWrite.All), toont de bestaande secrets van de app met hun verloopdatum
en voegt een nieuw client secret toe dat standaard 100 jaar geldig is.
Bestaande secrets worden NIET verwijderd: werk eerst de koppeling bij met het nieuwe
secret en verwijder het oude daarna zelf.
De waarde van het secret wordt maar EEN keer getoond. Sla hem direct veilig op.
.PARAMETER Tenant
Admin-account (bv. admin@bedrijf.onmicrosoft.com). Wordt gevraagd als het leeg is.
.PARAMETER AppId
Application (client) ID van de app-registratie (een Object ID werkt ook).
Wordt gevraagd als het leeg is.
.PARAMETER DisplayName
Omschrijving van het secret zoals zichtbaar in de Entra-portal.
.PARAMETER Years
Aantal jaren tot het secret verloopt (standaard 100).
.NOTES
Modules: Microsoft.Graph.Authentication (alleen deze Graph-module is nodig)
Rol van het admin-account: Application Administrator, Cloud Application Administrator,
Global Admin, of eigenaar van de app-registratie.
Versies:
1.1.0 Aanmelden zoals Export-EntraUserRights (admin-account vragen, tenant uit domein,
LoginHint, alleen Microsoft.Graph.Authentication); AppId wordt in de console
gevraagd i.p.v. vast in het script; bestaande secrets met verloopdatum worden
vooraf getoond.
1.0.0 Eerste versie.
.EXAMPLE
.\New-AppClientSecret.ps1
Vraagt om het admin-account en de Application (client) ID.
.EXAMPLE
.\New-AppClientSecret.ps1 -Tenant admin@bedrijf.nl -AppId 71bb67a7-6838-40b6-bac8-705dd28d946d -DisplayName 'Koppeling X'
#>
[CmdletBinding()]
param(
[string]$Tenant,
[string]$AppId,
[string]$DisplayName,
[ValidateRange(1, 200)]
[int]$Years = 100
)
$ErrorActionPreference = 'Stop'
$scriptVersion = '1.1.0'
function Write-Section { param([string]$Title) Write-Host "`n=== $Title ===" -ForegroundColor Cyan }
function Write-Warn { param([string]$Msg) Write-Host " ! $Msg" -ForegroundColor Yellow }
function Write-Ok { param([string]$Msg) Write-Host " + $Msg" -ForegroundColor Green }
function Write-Info { param([string]$Msg) Write-Host " $Msg" -ForegroundColor DarkGray }
function Write-Fail { param([string]$Msg) Write-Host " x $Msg" -ForegroundColor Red }
function Get-FirstLine { param($ErrorRecord) ("$($ErrorRecord.Exception.Message)" -split "`r?`n")[0] }
function Format-Dt {
param($Value)
if (-not $Value) { return '' }
try { return ([datetime]$Value).ToLocalTime().ToString('yyyy-MM-dd HH:mm') } catch { return "$Value" }
}
# ============================================================================
# 0. Controles en invoer
# ============================================================================
Write-Host ''
Write-Host "New-AppClientSecret v$scriptVersion - nieuw client secret voor een app-registratie" -ForegroundColor White
if (-not (Get-Module -ListAvailable -Name Microsoft.Graph.Authentication)) {
Write-Fail 'Module Microsoft.Graph.Authentication ontbreekt. Installeer met:'
Write-Host ' Install-Module Microsoft.Graph.Authentication -Scope CurrentUser' -ForegroundColor Yellow
return
}
if (-not $Tenant) { $Tenant = Read-Host -Prompt 'Admin-account (bv. admin@bedrijf.onmicrosoft.com)' }
$Tenant = "$Tenant".Trim()
if ($Tenant -notmatch '^[^@\s]+@[^@\s]+\.[^@\s]+$') { Write-Fail "Ongeldig admin-account: '$Tenant'"; return }
if (-not $AppId) { $AppId = Read-Host -Prompt 'Application (client) ID van de app' }
$AppId = "$AppId".Trim().Trim('"').Trim('{', '}')
$guid = [guid]::Empty
if (-not [guid]::TryParse($AppId, [ref]$guid)) { Write-Fail "Ongeldige Application ID (geen GUID): '$AppId'"; return }
$AppId = $guid.ToString()
if (-not $DisplayName) {
$DisplayName = (Read-Host -Prompt "Omschrijving van het secret (Enter = 'Client secret $(Get-Date -Format 'yyyy-MM-dd')')").Trim()
if (-not $DisplayName) { $DisplayName = "Client secret $(Get-Date -Format 'yyyy-MM-dd')" }
}
# ============================================================================
# 1. Verbinden
# ============================================================================
Write-Section '1. Verbinden met Microsoft Graph'
$loadedAuth = Get-Module Microsoft.Graph.Authentication
if ($loadedAuth) { $authVer = $loadedAuth.Version }
else {
$authVer = (Get-Module -ListAvailable Microsoft.Graph.Authentication | Sort-Object Version -Descending | Select-Object -First 1).Version
Import-Module Microsoft.Graph.Authentication -RequiredVersion $authVer -ErrorAction Stop
}
Write-Info "Microsoft.Graph.Authentication $authVer geladen"
$scopes = @('Application.ReadWrite.All')
$mgParams = @{ Scopes = $scopes; NoWelcome = $true; ContextScope = 'Process'; ErrorAction = 'Stop' }
if ($Tenant -match '^[^@\s]+@([^@\s]+\.[^@\s]+)$') {
$mgParams.TenantId = $Matches[1]
if ((Get-Command Connect-MgGraph).Parameters.ContainsKey('LoginHint')) { $mgParams.LoginHint = $Tenant }
}
Write-Host " Aanmelden: Microsoft Graph ($Tenant)..." -ForegroundColor Cyan
try { Connect-MgGraph @mgParams | Out-Null }
catch { Write-Fail "Aanmelden bij Graph mislukt: $(Get-FirstLine $_)"; return }
$mgCtx = Get-MgContext
if ($mgCtx.Account -and $mgCtx.Account -ne $Tenant) { Write-Warn "Graph is aangemeld als $($mgCtx.Account), niet als $Tenant." }
if ($mgCtx.Scopes -notcontains 'Application.ReadWrite.All') { Write-Warn 'Recht Application.ReadWrite.All is niet toegekend; aanmaken kan mislukken (tenzij je eigenaar van de app bent).' }
Write-Ok "Aangemeld als $($mgCtx.Account) (tenant $($mgCtx.TenantId))"
try {
# ========================================================================
# 2. App opzoeken
# ========================================================================
Write-Section '2. App-registratie opzoeken'
$select = 'id,appId,displayName,passwordCredentials'
$app = $null
$r = Invoke-MgGraphRequest -Method GET -OutputType PSObject -ErrorAction Stop `
-Uri "https://graph.microsoft.com/v1.0/applications?`$filter=appId eq '$AppId'&`$select=$select"
if (@($r.value).Count) { $app = @($r.value)[0] }
if (-not $app) {
# Misschien is de Object ID opgegeven in plaats van de Application ID
try {
$app = Invoke-MgGraphRequest -Method GET -OutputType PSObject -ErrorAction Stop `
-Uri "https://graph.microsoft.com/v1.0/applications/$AppId`?`$select=$select"
} catch { $app = $null }
}
if (-not $app) {
Write-Fail "Geen app-registratie gevonden met Application ID of Object ID '$AppId' in deze tenant."
Write-Info 'Let op: de Application ID van een enterprise app (service principal) van een andere tenant kan hier niet; het secret moet in de tenant van de app-registratie zelf.'
return
}
Write-Ok "Gevonden: $($app.displayName)"
Write-Info "Application ID: $($app.appId)"
Write-Info "Object ID : $($app.id)"
$now = (Get-Date).ToUniversalTime()
$existing = @($app.passwordCredentials)
if ($existing.Count) {
Write-Host ''
Write-Host ' Bestaande secrets:' -ForegroundColor Cyan
$existing | Sort-Object { [datetime]$_.endDateTime } | ForEach-Object {
$end = [datetime]$_.endDateTime
$status = if ($end.ToUniversalTime() -lt $now) { 'VERLOPEN' }
elseif ($end.ToUniversalTime() -lt $now.AddDays(30)) { 'verloopt binnen 30 dagen' }
else { 'geldig' }
[pscustomobject]@{
Omschrijving = $_.displayName
Hint = $_.hint
Verloopt_op = Format-Dt $_.endDateTime
Status = $status
SecretId = $_.keyId
}
} | Format-Table -AutoSize | Out-Host
} else {
Write-Info 'Deze app heeft nog geen client secrets.'
}
$ans = Read-Host " Nieuw secret '$DisplayName' aanmaken, $Years jaar geldig? (J/N)"
if ($ans -notmatch '^[JjYy]') { Write-Warn 'Afgebroken, er is niets aangemaakt.'; return }
# ========================================================================
# 3. Secret aanmaken
# ========================================================================
Write-Section '3. Client secret aanmaken'
$body = @{
passwordCredential = @{
displayName = $DisplayName
startDateTime = $now.ToString('yyyy-MM-ddTHH:mm:ssZ')
endDateTime = $now.AddYears($Years).ToString('yyyy-MM-ddTHH:mm:ssZ')
}
} | ConvertTo-Json -Depth 4
try {
$secret = Invoke-MgGraphRequest -Method POST -OutputType PSObject -ErrorAction Stop `
-Uri "https://graph.microsoft.com/v1.0/applications/$($app.id)/addPassword" `
-Body $body -ContentType 'application/json'
} catch {
$msg = Get-FirstLine $_
if ($msg -match 'policy|lifetime|CredentialLifetime') {
Write-Fail "Geweigerd door een app management policy in de tenant (maximale levensduur van secrets): $msg"
Write-Info 'Draai opnieuw met een kortere looptijd, bv. -Years 2.'
} else {
Write-Fail "Aanmaken mislukt: $msg"
}
return
}
Write-Ok 'Client secret aangemaakt.'
Write-Host ''
Write-Host ' De waarde wordt maar EEN keer getoond. Sla hem nu veilig op!' -ForegroundColor Yellow
[pscustomobject]@{
App = $app.displayName
TenantId = $mgCtx.TenantId
ClientId = $app.appId
SecretId = $secret.keyId
Omschrijving = $secret.displayName
Geldig_vanaf = Format-Dt $secret.startDateTime
Verloopt_op = Format-Dt $secret.endDateTime
SecretWaarde = $secret.secretText
} | Format-List | Out-Host
try {
Set-Clipboard -Value $secret.secretText
Write-Info 'De waarde van het secret staat ook op het klembord.'
} catch { }
if ($existing.Count) {
Write-Info 'Oude secrets zijn niet verwijderd. Verwijder ze in de Entra-portal zodra de koppeling het nieuwe secret gebruikt.'
}
}
finally {
Disconnect-MgGraph -ErrorAction SilentlyContinue -WarningAction SilentlyContinue | Out-Null
Write-Info 'Verbinding met Graph verbroken.'
}