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".
Related
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.
when I send a request through powershell to rest api Postmarkapp I have these errors
When use metod get
Invoke-RestMethod : Cannot send a content-body with this verb-type.
When use metod post
Server Error in '/' Application. The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /deliverystats
Script
$Uri = 'https://api.postmarkapp.com/deliverystats'
Invoke-RestMethod $Uri -Method Post -Headers #{'X-Postmark-Server-Token' =" Token" } -ContentType "application/json" |
The script you provided wasn't complete - it ends with a |.
A valid token is required before executing a request or you'll get this error:
Invoke-RestMethod : {"ErrorCode":10,"Message":"No Account or Server API tokens were supplied in the HTTP headers. Please add a header for either
X-Postmark-Server-Token or X-Postmark-Account-Token."}
Your code had ' Token', which is a constant and is probably not a valid value for the X-Postmark-Server-Token or X-Postmark-Account-Token header. You didn't show how $Token was set, but it probably should have been something like this:
$Token = 'xxxxxxxxxxxxx' #your account specific token
$uri = 'https://api.postmarkapp.com/deliverystats'
Then add the headers like this (with a $ before Token):
Invoke-RestMethod $Uri -Method Get -Headers #{'X-Postmark-Server-Token' ="$Token" } -ContentType "application/json"
I am having trouble calling smartsheets api with powershell Invoke-Restmethod cmdlet.
The attached script has worked before. See error message regarding SSL/TLS below.
$apiKey = "**********"
$url = "https://api.smartsheet.com/2.0/sheets"
$get_headers = #{"Authorization" = "Bearer " + $apiKey}
$put_headers = #{}
$put_headers.Add("Authorization", "Bearer " + $apiKey)
$put_headers.Add("Content-Type", "application/json")
$response = Invoke-RestMethod -Uri $url -Headers $get_headers
Invoke-RestMethod : The request was aborted: Could not create SSL/TLS secure
channel.
Is there anyway around this error?
The Smartsheet API dropped support for TLS 1.0, which is the default for Powershell.
The link Palansen shared above has some good solutions. Basically, you'll need to tell Powershell to use TLS 1.2 when invoked.
I am trying to connect to Keyvault with my Azure Function using PowerShell.
The Managed Service Identity (MSI) has been turned on, and in Keyvault I granted the MSI 'get' and 'list' access policies.
Using the script below I successfully get an access token, but when I make the request to Keyvault I always receive a 401 response.
$vaultName = $Env:KeyVaultName
$vaultSecretName = $Env:VaultSecretName
$tokenAuthURI = $Env:MSI_ENDPOINT + "?resource=https://vault.azure.net/&api-version=2017-09-01"
$tokenResponse = Invoke-RestMethod -Method Get -Headers #{"Secret"="$env:MSI_SECRET"} -Uri $tokenAuthURI
$accessToken = $tokenResponse.access_token
$headers = #{ 'Authorization' = "Bearer $accessToken" }
$queryUrl = "https://$vaultName.vault.azure.net/keys/" +$vaultSecretName + "?api-version=2016-10-01"
$keyResponse = Invoke-RestMethod -Method GET -Uri $queryUrl -Headers $headers
Any idea why the token is not sufficient?
Try changing the resource URI to https://vault.azure.net (with no trailing slash). The token validation on the server expects the exact same string as it returns in the 401 response's WWW-Authenticate header. In general, Key Vault returns 401 for cases where the token is missing or fails validation (three common cases are the token is expired, has an incorrect resource URI, or was issued by a different tenant than the vault is associated with).
Currently, following is how I am sending request from PS to update a parameter:
$pair="$("username"):$("password")"
$encodedCreds=[System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue="Basic $encodedCreds"
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", $basicAuthValue)
$headers.Add("Content-Type", 'text/plain')
$headers.Add("Origin", 'https://teamcity.server.io')
Invoke-RestMethod -Method Put -Uri $url -Headers $headers -Body $updated_version
But I do not want my username and password mentioned like this anymore.
What other ways do I have to authenticate myself for HTTP requests made within from TeamCity Build Step through PS?
Had to use the basic auth but instead of using my own credentials used a super user created by the dev ops that is available to everyone in the company.