ExpiredAuthenticationToken in FunctionApp - azure

I have a powershell script that connects to the ADO API and shows me a pool of agents. When I run it locally it works for me, but unfortunately there is already a bug in Function App
401 Unauthorized
{
"error": {
"code": "ExpiredAuthenticationToken",
"message": "The access token expiry UTC time '12/22/2022 2:49:41 PM' is earlier than current UTC time '12/22/2022 2:53:08 PM'."
}
}
This is a new generated PAT and it is active.
Script:
$personalToken = "t0k3n"
$patToken = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($personalToken)"))
$repoHeader = #{"Authorization"="Basic $patToken"}
Write-Output $repoHeader
$repoUrl = [string]::Format("https://dev.azure.com/org/_apis/distributedtask/pools?api-version=5.1")
Write-Output $repoUrl
$output = Invoke-RestMethod -Uri $repoUrl -Method Get -ContentType "application/json; charset=utf-8; api-version=6.0" -Headers $repoHeader -MaximumRedirection 10
Write-Output $output
foreach ($outputValue in $output.value)
{
Write-Output $outputValue.name
}
I have no idea why this works locally and not in Function App

This may seem strange.. But it was enough to refresh the page, because Cloud Shell has a certain time of operation, after which it throws you out of the session..

Related

Azure AutomationAccount DSC scripts debug

I am running a DSC script from an Azure automation account to configure Windows VMs. It downloads files from a storage account in Azure to hosts for more configurations. If I hardcode the storage SAS token, it works fine. But I would like to get the SAS token in the DSC script. I use managed identity of the Automation account and assigned proper IAM access in storage account. I am able to get the SAS token in a test runbook script, but not in DSC script.
I got the main part of the code from
https://learn.microsoft.com/en-us/azure/automation/enable-managed-identity-for-automation
The error I am getting indicates that the SAS token is not generated correctly, but I can't find a way to see what the error msgs are from this part of the code in DSC when it executed.
any help/suggestion is appreciated!
Configuration DSCtest {
Import-DscResource -ModuleName 'PSDesiredStateConfiguration'
$resource= "?resource=https://management.azure.com/"
$url = $env:IDENTITY_ENDPOINT + $resource
$Headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$Headers.Add("X-IDENTITY-HEADER", $env:IDENTITY_HEADER)
$Headers.Add("Metadata", "True")
$accessToken = Invoke-RestMethod -Uri $url -Method 'GET' -Headers $Headers
$Atoken = $accessToken.access_token
Write-Output $Atoken
$toDate = (Get-Date).AddDays(4).toString("yyyy-MM-ddT00:00:00Z")
$params = #{canonicalizedResource="/file/storageacnt/exec";signedResource="c";signedPermission="rcw";signedProtocol="https";signedExpiry=$toDate}
$jsonParams = $params | ConvertTo-Json
$sasResponse = Invoke-WebRequest -Uri https://management.azure.com/subscriptions/xxxxxxxxxxxx/resourceGroups/rg-xxxxx/providers/Microsoft.Storage/storageAccounts/storageaccnt/listServiceSas/?api-version=2017-06-01 -Method POST -Body $jsonParams -Headers #{Authorization="Bearer $Atoken"} -UseBasicParsing
$sasContent = $sasResponse.Content | ConvertFrom-Json
$sasCred = $sasContent.serviceSasToken
write-host $sasCred
$sasToken = "?$sasCred"
Node LocalHost {
....

Why I cannot authenticate an app in Azure

I am trying to authenticate app in azure, but getting the following error,
Response status code does not indicate success: 401 (Unauthorized).
Authentication is done using a powershell cmdlet,
function Get-AzureToken {
Param(
[Parameter(Mandatory)][String]$TenantId,
[Parameter(Mandatory)][String]$ApplicationId,
[Parameter(Mandatory)][String]$Secret,
[Parameter()][string]$apiEndpointUri = "https://management.azure.com/.default"
)
$encodedSecret = [System.Web.HttpUtility]::UrlEncode($secret)
$RequestAccessTokenUri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
$body = "grant_type=client_credentials&client_id=$applicationId&client_secret=$encodedSecret&scope=$apiEndpointUri"
$contentType = 'application/x-www-form-urlencoded'
Write-Information "Fetching token for service principal"
try {
$Token = Invoke-RestMethod -Method Post -Uri $RequestAccessTokenUri -Body $body -ContentType $contentType
if (!$token) {
throw "Something went wrong getting token"
}
}
catch {
write-error $_.Exception.Message
write-error "Failed to get token" -ErrorAction Stop
}
return "$($Token.access_token)"
}
Error in GitHub actions:
Try URLEncode on the scope URI.
Also use double slashes for the URL:
https://github.com/MicrosoftDocs/azure-docs/issues/68642?msclkid=908717bbb41f11eca828738506359fcb

'Invoke-RestMethod : The remote server returned an error: (401) Unauthorized' only in Azure DevOps release pipeline

I have a PowerShell script that works from a local PowerShell but when it runs in a PowerShell task in an Azure DevOps release pipeline it returns Invoke-RestMethod : The remote server returned an error: (401) Unauthorized.
The user is added as a project member within Azure DevOps and I have also created a Personal Access Token with full access.
function Get-HttpBasicHeader([string]$username, [string]$password)
{
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $userName, $password)))
return #{Authorization=("Basic {0}" -f $base64AuthInfo)}
}
$headers = Get-HttpBasicHeader $userName $password
$url = "https://transpa.vsrm.visualstudio.com/transPA/_apis/release/releases?definitionId=42&definitionEnvironmentId=61&api-version=5.0"
$response = Invoke-RestMethod -Uri $url -Method Get -Headers $headers
What am I doing wrong? Let me know if I should provide any additional information.

Kudu zipdeploy with POWERSHELL throwing The remote server returned an error: (500) Internal Server Error

We are trying to deploy web app using POWER SHELL with KUDU ZIPDEPLOY, and it's failing with (500) Internal Server Error.
Interestingly it is working fine with CURL command.
The main difference is, in CURL I don't have use PROXY, but POWER SHELL it is asking for PROXY details. I guess this might be I am deploying from organization network.
$username = "`*********"
$password = "********"
$pair = "$($username):$($password)"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue = "Basic $encodedCreds"
$Headers = #{
Authorization = $basicAuthValue
}
$deployUri = "https://testexploreazurewebsites.scm.azurewebsites.net/api/zipdeploy?isAsync=true"
$proxyUri = [Uri]$null
$proxy = [System.Net.WebRequest]::GetSystemWebProxy()
if ($proxy)
{
$proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials
$proxyUri = $proxy.GetProxy($deployUri)
}
$sourceFilePath = "FilePath.zip"
$responseHeaders = Invoke-WebRequest -Uri $deployUri -ContentType "multipart/form-data" -Method Post -Proxy $proxyUri -ProxyUseDefaultCredentials -Headers $Headers `
-InFile $sourceFilePath `
-TimeoutSec 600000
It was working good till few days back, suddenly stopped working.
Any help please?
Updates and answer
From Kudu log files, the error description is : Missing content-type boundary.
Followed SF post powershell invoke-restmethod multipart/form-data to solve it.

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