connecting to azure rest api using powershell resulting in StatusCode : 203 StatusDescription : Non-Authoritative Information - azure

I am able to connect fine to azure API's using a PAT token in postman, however am not able to authenticate using powershell.
After playing around with different authorization passing I am still stuck with getting the html page for the sign in returned. Here is a sample request I am making
Invoke-RestMethod https://feeds.dev.azure.com/xx/x/_apis/packaging/Feeds/x/Packages -Headers #{Authorization="Token :xxx"}

After much searching I came across https://www.opentechguides.com/how-to/article/azure/201/devops-rest-powershell.html. Here is a simplified snippet that allowed my request to go through successfully.
#enter your token in pat token
$pat = "xxx"
# Create header with PAT
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($pat)"))
$header = #{authorization = "Basic $token"}
#enter your url in projects url
$projectsUrl = "https://feeds.dev.azure.com/xx/x/_apis/packaging/Feeds/x/Packages -Headers"
$projects = Invoke-RestMethod -Uri $projectsUrl -Method Get -ContentType "application/json" -Headers $header

Related

Unable to retrieve token from Azure API

I am trying to get a token to be able to retrieve Groups information in Azure AD
This is my powershell script against the API:
Invoke-RestMethod -Method POST -Uri 'https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/token?api-version=1.6'
-Header #{'Content-type' = 'application/x-www-form-urlencoded'}
-Body '{grant_type=client_credentials&client_id=<clientID>&scope=https://graph.microsoft.com/.default&client_secret=<clientSecret> }'
I keep getting this error: {"error":"invalid_request","error_description":"AADSTS900144: The request body must contain the following parameter: 'grant_type'.\r\nTrace ID:
Your body ia malformed, just do:
$body = #{
Grant_Type = 'client_credentials'
Scope = 'https://graph.microsoft.com/.default'
Client_Id = $ClientID
Client_Secret = $Secret
}
$con = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantid/oauth2/v2.0/token" -Method 'Post' -Body $body
$token = $con.access_token

my Azure ML api rest return an empty object

My issue
I try using REST API for machine learning. The following PowerShell doesn't fail, but return an empty objet, whatever the API I am testing.
my SPN has contributor permission, I made grant consent and I checked I get a token.
the doc I was using:
https://learn.microsoft.com/fr-fr/rest/api/azureml/quotas/list
I tested several other GET API as well.
I don't know what to do more. Any idea?
My Powershell code
$tenant_id = "XXXXXXXXXXXXXXXXXXX"
$ApplicationId = "XXXXXXXXXXXXXXX"
$spn_client_secret = "XXXXXXXXXXXXX"
$subscriptionid="XXXXXXXXXXXX"
$uri = "https://login.microsoftonline.com/$tenant_id/oauth2/token"
$BodyText = "grant_type=client_credentials&client_id=$ApplicationId&resource=https://management.azure.com&client_secret=$spn_client_secret"
# GET TOKEN
$Response = Invoke-RestMethod -Method POST -Body $BodyText -Uri $URI -ContentType application/x-www-form-urlencoded
$aad_access_token = $Response.access_token
# tested, I effectively have a token
# READ ml
$urllist = "https://management.azure.com/subscriptions/$subscriptionid/providers/Microsoft.MachineLearningServices/locations/westeurope/quotas?api-version=2021-03-01-preview"
$headers = #{"Authorization" = "Bearer " + $aad_access_token}
Invoke-RestMethod -Method GET -HEADERS $headers -Uri $urllist -ContentType application/x-www-form-urlencoded
I found what happend and I am a little bit confused.
The resource was empty, because I completely forgot to create a compute!

PowerShell- Use Credentials instead of Basic Bas64 with Token to Invoke-RestMethod against AzureDevops

I have PowerShell scripts that I run to kick off a build in Azure DevOps as well as doing lots of things in Azure DevOps using the Rest API. I am currently using the token that is converted to Base64 using basic in the header to authenticate. If there a way of using -Credentials (Get-Credentials) with the token instead of a base64 header encoded token when using Invoke-RestMethod? Below is a sample for connecting with the Base64 token and Basic.
Sample script that lists Projects:
$token = "##############################################"
$UriOrg = "https://dev.azure.com/myADO/"
$AzureDevOpsAuthenicationHeader = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($token)")) }
$uriProcess = $UriOrg + "_apis/process/processes?api-version=5.1"
Invoke-RestMethod -Uri $uriProcess -Method get -Headers $AzureDevOpsAuthenicationHeader
Although Get-Credential is designed to get a credential using a username and password, you can of course also use it to have someone enter the token..
Something like
$cred = Get-Credential -Message 'Please enter the AzureDevops Token in the Password field' -UserName 'AzureDevops'
if ($cred) {
$token = $cred.GetNetworkCredential().Password
$authHeader = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($token)")) }
$UriOrg = 'https://dev.azure.com/myADO/'
$uriProcess = $UriOrg + "_apis/process/processes?api-version=5.1"
Invoke-RestMethod -Uri $uriProcess -Method Get -Headers $authHeader
}
Another option would be to create your own form where it is also possible to enter the Uri for the organization, because Get-Credential does not accept usernames like https://dev.azure.com/myADO/

Erorr exporting Azure sql database to blob storage with powershell

I'm trying to use Azure management API to export a SQL database to a bacpac file in a blob storage. The process seems fairly simple: obtain a token, and then:
$sqlAzureBackupHeaders = #{
Authorization = "Bearer $accessToken"
}
$sqlAzureBackupParams = #{
storageKey = "<key-goes-here>",
storageUri = "http://mystorageacct.blob.core.windows.net/my-blob-container/export-name.bacpac",
storageKeyType = "StorageAccessKey",
administratorLogin = "<sql-user>",
administratorLoginPassword = "<sql-password>",
authenticationType = "SQL"
}
$sqlAzureApiUri = "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.Sql/servers/<server-name>/databases/<database-name>/export?api-version=2014-04-01"
Invoke-RestMethod -Uri $sqlAzureApiUri -Method Post -Headers $sqlAzureBackupHeaders -Body $sqlAzureBackupParams
This results in an error:
Invoke-RestMethod : Receivera:InternalServiceFaultThe server was unable to process the request due to an internal error. For more
information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the
<serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing
as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs.
At D:\Users\protec-admin\Desktop\run-backups.ps1:140 char:1
+ Invoke-RestMethod -uri $sqlAzureApiUri -Method Post -Headers $sqlAzur ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I tried using Invoke-WebRequest and converting body to json string - with the same result.
When I try the same call using Postman, it works fine, so there's something with making the call from powershell that's not working correctly.
How can I get this working from powershell?
According to my test, the rest API just accept the json body. Please use ConvertTo-Json to convert the body to json.
For example
$headers=#{"Authorization" = "Bearer "+$token}
$body=#{
"storageKeyType"= "StorageAccessKey";
"storageKey"= "<your storage account access key>";
"storageUri"= "https://blobstorage0516.blob.core.windows.net/sample/testbacpac2.bacpac";
"administratorLogin"= "<SQL admin>";
"administratorLoginPassword"= "<SQL admin passsword>";
"authenticationType"= "SQL"
}|ConvertTo-Json
$sqlAzureApiUri = "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.Sql/servers/<server-name>/databases/<database-name>/export?api-version=2014-04-01"
Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -Body $body -UseBasicParsing -ContentType "application/json"

How to authenticate for https://management.azure.com api?

I want to retrieve data on my DNS zones through a API call:
$api = "?api-version=2018-05-01"
$pat = "Bearer $env:System_AccessToken"
Write-Host "### PAT ###"
Write-Host $pat
$DNSInformation = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.Network/dnsZones/$zoneName/$recordType/$relativeRecordSetName$api"
Write-Host "###"
Write-Host $DNSInformation
Write-Host "###"
$x = Invoke-RestMethod -Uri $DNSInformation -Headers #{Authorization = $pat } -Method Get
When I run this script I get:
The remote server returned an error: (401) Unauthorized.
When I navigate to the URL I get:
error: {
code: "AuthenticationFailed",
message: "Authentication failed. The Authorization header is missing."
}
I think the issue is that I can't use the $env:System_AccessToken token to get on the management api. But I can't find information what kind of authentication is needed.
As the error mentions, the authorization header is incorrect.
$URI = "https://management.azure.com/providers/microsoft.resources/checkresourcename?api-version=2014-01-01"
Invoke-RestMethod -Uri $URI -Method GET -Headers $authHeader
You can use a couple of approaches to create your header:
As you mentioned - Azure Powershell to check resource names
By creating Bearer token : Powershell Script to delete unused resources in Azure

Resources