Search code examples
powershellazure-devopsazure-devops-rest-api

Powershell Invoke-RestMethod not authenticated with PAT for Azure DevOps


I'm trying to invoke the REST API of our Azure DevOps project, and I'm getting some results I don't expect.

I can get results using LinqPad, but using Powershell fails.

My Script

$env:Build_BuildId = 2468
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("myPAT"))
$env:System_TeamProject = "myProject"

$url = "https://dev.azure.com/myorg/$env:System_TeamProject/_apis/build/builds/$env:Build_BuildId/changes?api-version=5.0"

$response = Invoke-RestMethod -Uri $url -Method Get -ContentType "application/json" -Headers @{ 
    Authorization = "Basic $token" 
}

Write-Host $response

The Response

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">




<html lang="en-US">
<head><title>

            Azure DevOps Services | Sign In

</title><meta http-equiv="X-UA-Compatible" content="IE=11;&#32;IE=10;&#32;IE=9;&#32;IE=8" />
    <link rel="SHORTCUT ICON" href="/favicon.ico"/>

    <link data-bundlelength="508485" data-bundlename="commoncss" data-highcontrast="/_static/tfs/M154_20190628.18/_cssbundles/HighContrast/vss-bundle-commoncss-vAEI_yKFIiS9jTVmCtAOiwe4cLPqdXnp6QCUVseU7jzk=" data-includedstyles="jQueryUI-Modified;Core;Splitter;PivotView" href="/_static/tfs/M154_20190628.18/_cssbundles/Default/vss-bundle-commoncss-vqjKBNZxfVQkGGn0rrvF7eh9DJDj__wqtFN85fVrIQn8=" rel="stylesheet" />
<link data-bundlelength="116162" data-bundlename="viewcss" data-highcontrast="/_static/tfs/M154_20190628.18/_cssbundles/HighContrast/vss-bundle-viewcss-v356iHjTFccxhkNidRJIEefQ92VqpWpa7rO4mdtAnDpM=" data-includedstyles="VSS.Controls" href="/_static/tfs/M154_20190628.18/_cssbundles/Default/vss-bundle-viewcss-vXHgBtK2hntEJYzWnMNhcJkJC-nUhp2m3BtF-jVlzOZA=" rel="stylesheet" />
... etc. etc.

I imagine that the request is given a response that would be rendered by a browser to be the signin landing page for azure devops.

enter image description here

I have double and triple checked my PAT and even create a few new full access versions w/ no change in behavior.


Ultimately this script is going to be run on the hosted agent, so I'm not too worried about this in the end, but I would like to not run the pipeline for testing the script if I don't need to.


Solution

  • $token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("myPAT")) is incorrect. myPAT should have a leading colon.

    Ex:

    $token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":myPAT"))