VSTS build running locally - error: "Microsoft Internet Explorer. Enhanced Security Configuration" - powershell

I'm running Windows 10 and making a script to handle/start VSTS builds.
Sample call (overriding properties for testing):
$env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI = "https://mytenancy.visualstudio.com/"
$env:SYSTEM_TEAMPROJECTID = "Project1"
$env:SYSTEM_DEFINITIONID = 5
#$env:SYSTEM_ACCESSTOKEN = "mytoken" - uncomment when running locally
$url = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECTID/_apis/build/definitions/$($env:SYSTEM_DEFINITIONID)?api-version=2.0"
Write-Host "URL: $url"
$definition = Invoke-RestMethod -Uri $url -Headers #{
Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}
Write-Host "Definition = $($definition | ConvertTo-Json -Depth 100)"
"Authenticated"
This script works fine on the server, but if I uncomment the $env:SYSTEM_ACCESSTOKEN and run locally, I get the following error:
Microsoft Internet Explorer\u0026#39;s Enhanced Security Configuration
is currently enabled on your environment. This enhanced level of
security prevents our web integration experiences from displaying or
performing correctly. To continue with your operation please disable
this configuration or contact your administrator.
I'm running Windows 10.
I've tried many things, including:
Turning off as much security as possible in Internet Options.
Fresh Token
Converting the token to a secure string
Converting to a Base64 string as detailed in the answer to this post
How can I authenticate locally?
EDIT (following accepted answer)
The accepted answer solved the problem. I think the two key points here were:
The correct encoding in conversion to Base64
Changing authentication from Bearer to Basic when running in this way (locally).
Final code:
$user = "[username]"
$accessToken="[token]"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$accessToken)))
$env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI = "https://mytenancy.visualstudio.com/"
$env:SYSTEM_TEAMPROJECTID = "Project1"
$checkBuildUrl = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$($env:SYSTEM_TEAMPROJECTID)/_apis/build/builds/$($requestedBuildId)?api-version=2.0"
$buildStatus = Invoke-RestMethod -Uri $checkBuildUrl -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}

Create a new access token and refer to this code to call the REST API through PowerShell:
$user = "[anything]"
$accessToken="[access token]"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$accessToken)))
...
Invoke-RestMethod -Uri $uri -Method Post -ContentType "application/json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Body $bodyJson
Regarding enhanced security, there is a similar issue:
Enhanced Security Error while Visual Studio Team Services Rest API

Related

need to add authentication header to azure devops api request

I'm trying to get information on my latest builds by sending a GET request to the Azure DevOps REST Api. I'm using Azure DevOps Server 2020 with the Patch 1 update. I need to add an authorization header to the request. The header I added is not working.
I'm doing the request in Powershell. Here's my code:
$PAT = 'personal access token'
$ENCODED = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($PAT))
$headers = #{
Authorization="Basic $ENCODED"
}
Invoke-RestMethod -Uri [azure devops server url]/[project name]/_apis/build/latest/Build?api-version=5.0 -Method Get -Headers $headers
When I run the code I get the error: Invoke Method: The format of value [PAT] is invalid
UPDATE:
I updated the header syntax. Now the reponse I get:
Invoke-RestMethod:
TF400813: Resource not available for anonymous access. Client authentication required. - Azure DevOps Server
I also tried passing my Azure DevOps username and password in the header like this:
$headers = #{
Authorization="Basic [domain\username]:[password]"
}
and I got this in response:
Invoke-RestMethod: Response status code does not indicate success: 401 (Unauthorized).
Do I have to enable some setting in Azure DevOps?
I usually reference to this demo to run REST API in PowerShell, it can work fine:
$uri = "request URI"
$pat = "personal access token"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "", $pat)))
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", ("Basic {0}" -f $base64AuthInfo))
$headers.Add("Content-Type", "application/json")
. . .
$body = "{
. . .
}"
Invoke-RestMethod -Uri $uri -Headers $headers -Body $body -Method POST
In your case, the issue seems is caused by the encoding. Try using ASCII or UTF8, instead of Unicode.
To view more details, you can see "Use personal access tokens".

Unable to authenticate against Azure DevOps _apis/distributedtask/variablegroups using PAT

I'm running a simple call to Azure DevOps API using Powershell:
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "{USER}","{PAT}")))
$url = "https://dev.azure.com/{ORG_NAME}/{PROJECT_NAME}/_apis/distributedtask/variablegroups/{ID}?api-version=5.0-preview.1"
Invoke-RestMethod -Uri $url -Method Get -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
The error is shown after:
Invoke-RestMethod: Response status code does not indicate success: 401 (Unauthorized).
Trying to figure out what's wrong, all is configured according to this and this articles.
The strange is that running a call against API without specifying the project is processed without errors:
$url2 = "https://dev.azure.com/{ORG_NAME}/_apis/projects?api-version=2.0"
Invoke-RestMethod -Uri $url2 -Method Get -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
Response:
count value
----- -----
5 {#{id=xxxxxxx-89f3-46b0-af7e-xxxxxxx; name=Xxxxx; description=F…
It seems your PAT is not authorized to access the Variable groups.
You can go to your PAT edit page to check if the PAT was assigned at least the Read permission for Variable groups. See below screenshot.
Grant the proper permission scope for your PAT, and try calling the rest api again.

Azure DevOps API - Set Board Options

I'm trying to do few things with Azure DevOps projects through Rest API, but I really quickly got stuck.
For example, I want to use the method "Set Board Options", documentation is here https://learn.microsoft.com/en-us/rest/api/azure/devops/work/boards/set%20board%20options?view=azure-devops-rest-5.1
Does anyone have an idea of how to find out which options (and how exactly) I can use? Is there any way to lookup these values in the Azure DevOps portal or somewhere else?
I was trying to use the .Net library (https://github.com/microsoft/azure-devops-dotnet-samples), but the situation there is the same. Method SetBoardOptions exists but takes Dictionary of strings as the first argument and there is no documentation on how to actually fill up this dictionary, which values are possible to use etc.
This API is in preview so I guess this is the reason why the docs so poor:
After a big search and tries, I think you can change 2 options in the board settings:
1) statusBadgeIsPublic - True or False.
2) cardReordering - 0 or 1.
I success to do it with PowerShell:
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,"MY-PAT")))
$headers = #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$URI = "https://dev.azure.com/{org}/{project}/{team}/_apis/work/boards/{board}?api-version=5.1"
$params = #{
"cardReordering"="1";
} | ConvertTo-Json
Invoke-RestMethod -Method Put -Uri $URI -Headers $headers -Body $params -ContentType 'application/json'

How would you access attributes of work items (Features, User Stories, Bugs, or Tasks) associated with a build in the release pipeline?

My team and I are trying to find a way to automatically build release notes and generate them in markdown to be put into a Wiki for users to access. I found a video from Microsoft where their team uses a process where they have release notes for each feature in their Feature objects, but they have manually query those objects and build a markdown file for each release manually. I'm sure by now they must have figured this out, but can't find anything from them yet on that.
Now, I have seen a couple of market place tools (Bravo Notes for one) that do this, but I figured there must be a way we can make a task ourselves that does this for us and automatically place the markdown file in our Wiki (after an approval process of course).
If anyone has any ideas on how I can accomplish this, please let me know. I'm not afraid of getting my hands dirty with some Powershell scripts.
You can use Azure DevOps Rest API to get the work item that associated to the build, then get work item details. create from the details a Markdown file and add it to the wiki.
Example to PowerShell script that do it (get work items asscoited with the build and print the AssignedTo field):
$user = ""
$token = "MY-PAT"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
$url = "https://dev.azure.com/{org}/{project}/_apis/build/builds/{buildId}/workitems?api-version=5.1"
$workItems = Invoke-RestMethod -Uri $url -Method Get -ContentType application/json -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$json = $workItems | ConvertTo-Json
$workItems.value.ForEach({
$workItem = Invoke-RestMethod -Uri $_.url -Method Get -ContentType application/json -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
Write-Host $workItem.fields.'System.AssignedTo'.displayName
})

VSTS build history for a Build definition

I have a VSTS build definitions in our project, Can i get the build results (passed/failed) that ran using that definition (builds started running using the definition since last 6 months) ?
Currently i am only getting last 20 build information ran from that build definition.
You can get it through Build REST API with PowerShell: Get a list of builds.
For example:
param(
[string]$sinceDate,
[string]$token,
[string]$defId
)
$uri="https://[acccount.visualstudio.com/DefaultCollection/[project]/_apis/build/builds?definitions=$defId&deletedFilter=1&minFinishTime=$sinceDate"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "test",$token)))
$result= Invoke-RestMethod -Method Get -Uri $Uri -ContentType "application/json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$statusResult=$result.value | select-object -Property id,buildNumber,result
Arguments:
-sinceDate "12/1/2017" -token "[personal access token]" -defId "94"