Connect to Azure with an authenticated account using an accessToken in a PowerShell Azure function

Viewed 118

Before I describe my problem, I want to clarify that I am not an Azure expert. So please excuse me if I say something wrong.

I have a PowerShell Azure Function that is secured with AAD. In my script (Az Funciton) I can get the accessToken and the AccountId from the request Header:

#Input bindings are passed in via param block.
param($Request, $TriggerMetadata)
$accountId = $Request.Headers['x-ms-client-principal-name']
$accessToken = $Request.Headers['x-ms-token-aad-access-token']

On my script, I use the Power Shell Az module and I want to connect to Azure with the following command:

Connect-AzAccount -AccessToken $accessToken -AccountId $accountId

Unfortunately, the connection to Azure is not working properly, I get the following error:

Unable to acquire token for tenant 'organizations' with error 'Authentication failed.'

I understood that it's not the right accessToken to use. Is it possible to have the right AccessToken and so use the Connect-AzAccount command with AccessToken option ?

I want to specify that the PowerShell script must be executed with the identity of the user who is calling my Azure function. Is my approach correct or is there another way to implement the same scenario?

Thanks for your help, Mehdi

1 Answers

I finally got a better understanding of the problem. Indeed, I was missing a configuration to allow my token to take into account the Azure Service Management API.

The configuration is possible from https://resources.azure.com/

Here is the configuration used:

"identityProviders": {
  "azureActiveDirectory": {
    "enabled": true,
    "registration": {
      "openIdIssuer": "https://sts.windows.net/e005f490-xxxx-4816-xxxx-b0ed7fa9ad58/",
      "clientId": "559740f9-xxxx-xxxx-9015-5b9dd6e595bb",
      "clientSecretSettingName": "MICROSOFT_PROVIDER_AUTHENTICATION_SECRET"
    },
    "login": {
      "loginParameters": [
        "response_type=code id_token",
        "resource=https://management.azure.com"
      ],
      "disableWWWAuthenticate": false
    }
...

I highly recommend this blog which really explains the entire idea: https://blog.bredvid.no/patterns-for-securing-your-azure-functions-2fef634f4020

Related