I'm writing a powershell script to rotate my PAT in my devbox. Here's what I've done:
PS> .\Rotate-Pat.ps1
Here's the code in Check-PatValidity.ps1:
$env:PAT | az devops login --organization "https://dev.azure.com/$organization"
$body = @{
displayName = $organization
scope = "vso.build vso.code_full vso.tokens vso.profile"
validTo = (Get-Date).AddDays(7).ToString("yyyy-MM-ddTHH:mm:ssZ")
allOrgs = $false
} | ConvertTo-Json
$response = Invoke-RestMethod -Uri "https://vssps.dev.azure.com/$organization/_apis/tokens/pats?api-version=7.1-preview.1" -Headers $headers -Method Post -Body $body -ContentType "application/json"
$prettyJson = $response | ConvertTo-Json -Depth 2
$prettyJson | Out-file $env:USERPROFILE\Downloads\patgenoutput.json -Encoding UTF8
if ($response) {
$newPat = $response.patToken.token
Write-Output "New PAT: $newPat"
}
Here's what I see as output (which is exactly the same as patgenoutput.json):
Looks like the html of Azure DevOps Login screen.
Questions:
Alternatively, make use of below modified script that asks user to login interactively and generates bearer token to call Azure DevOps API for PAT creation:
$organization = "demodevOps25"
Write-Output "Logging into Azure..."
$loginOutput = az login --tenant "xxxxxxxxx.onmicrosoft.com" --only-show-errors
try {
$token = az account get-access-token --resource "499b84ac-1321-427f-aa17-267ca6975798" | ConvertFrom-Json
} catch {
Write-Error "Failed to retrieve access token. Please check your Azure login status."
exit
}
$headers = @{
Authorization = "Bearer $($token.accessToken)"
'Content-Type' = 'application/json'
}
$body = @(
@{
displayName = $organization
scope = "vso.build vso.code_full vso.tokens vso.profile"
validTo = (Get-Date).AddDays(7).ToString("yyyy-MM-ddTHH:mm:ssZ")
allOrgs = $false
}
) | ConvertTo-Json
$response = Invoke-RestMethod -Uri "https://vssps.dev.azure.com/$organization/_apis/tokens/pats?api-version=7.1-preview.1" `
-Headers $headers `
-Method Post `
-Body $body `
-ContentType "application/json"
if ($response -and $response.patToken) {
$newPat = $response.patToken.token
Write-Output "New PAT generated: $newPat"
$outputPath = Join-Path $env:USERPROFILE "Downloads\patgenoutput.json"
$response | ConvertTo-Json -Depth 3 | Out-File $outputPath -Encoding UTF8
Write-Output "PAT details saved to: $outputPath"
} else {
Write-Error "Failed to generate PAT. Check the request body and API version."
}
Output:
To confirm that, I checked the saved file where new PAT details displayed successfully as below:
Azure DevOps Portal: