Skip to content

Instantly share code, notes, and snippets.

@tkalve
Created December 22, 2025 15:01
Show Gist options
  • Select an option

  • Save tkalve/b8b7f156dec8ea68fd87c7c437392546 to your computer and use it in GitHub Desktop.

Select an option

Save tkalve/b8b7f156dec8ea68fd87c7c437392546 to your computer and use it in GitHub Desktop.
Powershell script to get a token for my app environment
<#
.SYNOPSIS
Get access token for a specified <app> environment
.DESCRIPTION
Fetches required secrets from Azure key vault, and used azure CLI to get a token.
.PARAMETER environment
Which <app> environment to authenticate against (eg. dev, test, prod)
Default: dev
#>
param (
[Alias("e")]
[string]$environment = "dev",
[Alias("s")]
[switch]$silent,
[Alias("c")]
[switch]$clipboard
)
[string] $environments = "dev", "test", "prod"
$banner = @"
__ _ _ _ _ _ _
/ / ___| |_( )__ __ _ ___| |_ __ _ | |_ ___ | | _____ _ __ / \
/ / / _ \ __|/ __| / _`` |/ _ \ __| / _`` | | __/ _ \| |/ / _ \ '_ \ / /
/ /__| __/ |_ \__ \ | (_| | __/ |_ | (_| | | || (_) | < __/ | | /\_/
\____/\___|\__||___/ \__, |\___|\__| \__,_| \__\___/|_|\_\___|_| |_\/
|___/
"@
if (!$silent) {
Write-Host -ForegroundColor White $banner
Write-Host ""
}
try {
$userName = (az account show --query "user.name" --output tsv)
if ($null -eq $username || -not $?) {
Write-Host
Write-Host -ForegroundColor White "Not logged in? Run 'az login' first."
Exit 1
}
if (!$environments.contains($environment)) {
Write-Host -ForegroundColor White "$environment is not a valid environment."
Exit 1
}
$environmentKeyvault = "<app>-{env}-kv".Replace("{env}", $environment)
if (!$silent) {
Write-Host "Logged in as $userName."
Write-Host "Using key vault $environmentKeyVault for <app> $environment."
Write-Host ""
}
$scope = (az keyvault secret show --vault-name $environmentKeyvault --name "AzureAd--Resource" --query "value" --output tsv)
if ([string]::IsNullOrEmpty($scope)) {
Write-Host -ForegroundColor White "Unable to get scope from keyvault."
Exit 1
}
$token = (az account get-access-token --scope $scope --query accessToken --output tsv)
if ([string]::IsNullOrEmpty($token)) {
Write-Host -ForegroundColor White "Did not get a token, not sure why :|"
Exit 1
}
if ($silent -eq $false) {
Write-Host "Retrieved token for <app> $environment, scope $scope"
Write-Host
}
if ($clipboard) {
Set-Clipboard -Value $token
if (!$silent) {
Write-Host "Token copied to clipboard."
}
}
else {
Write-Output $token
}
Exit 0
}
catch {
$errorMessage = ConvertFrom-Json $_.ErrorDetails.Message
Write-Host
Write-Host $errorMessage.error
Write-Host $errorMessage.error_description
Exit 1
}
if ($silent -eq $false) {
Write-Host "Done!"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment