I need to prepare automation for checking some Azure Devops object details like: list of az devops projects, list of projects, details about pipelines etc. I have powershell code prepared, I have SPN created in Azure AD, I grant API permissions for SPN (Azure Devops full access - application permissions). I am using below presented code to login as SPN account:
$SecuredPassword = ConvertTo-SecureString -String $AppSecret -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AppId, $SecuredPassword
Connect-AzAccount -ServicePrincipal -TenantId $TenantId -Credential $Credential
then I am using code below to generate token and send request to Azure devops rest api endpoint. I still facing error messages like: TF400813: The user is not authorized to access this resource.
and 401 - Uh-oh, you do not have access. The request requires authentication.
$token = (Get-AzAccessToken -ResourceUrl "499b84ac-1321-427f-aa17-267ca6975798").Token
$URL = 'https://dev.azure.com/orgname/ADOorgName/_apis/pipelines/52/runs?api-version=6.0-preview.1'
$header = @{
'Authorization' = 'Bearer ' + $token
'Content-Type' = 'application/json'
}
$body = @"
{
"resources": {
"repositories": {
"self": {
"refName": "refs/heads/main"
}
}
}
}
"@
Invoke-RestMethod -Method Post -Uri $URL -Headers $header -Body $body