Search code examples
powershellazure-application-insightsbearer-tokenazure-log-analytics

How to configure Basic Logs in Azure Log Analytics - how to get bearer token?


I have Azure Log Analytics and Azure Application Insights. I want to set certain tables in my Log Analytics to "Basic Logs" because that is cheaper. First I want to just check the settings for these tables.

I am trying to follow this article: https://learn.microsoft.com/en-us/azure/azure-monitor/logs/basic-logs-configure?tabs=api-2

The article tells me to get a bearer token by following this other article: https://social.technet.microsoft.com/wiki/contents/articles/51140.azure-rest-management-api-the-quickest-way-to-get-your-bearer-token.aspx

I extract a bearer token from the Azure Portal using the developer tools. It looks like this (a few hundred characters long): Bearer ey...A.

I then try to do this in PowerShell:

$BearerToken = "Bearer ey...A"
$uri = "https://management.azure.com/subscriptions/<subscriptionId>/resourcegroups/<resourceGroupName>/providers/Microsoft.OperationalInsights/workspaces/<workspaceName>/tables/<tableName>?api-version=2021-12-01-preview"
Invoke-WebRequest $uri -Headers @{Authorization = $BearerToken}

This gives me:

{"error":{"code":"InvalidAuthenticationToken","message":"The access token is invalid."}}

In my PowerShell session I am logged in as the same user as in the Portal (using az login).

Might it be a rights issue? I have "Owner" and "Contributor" access to the Log Analytics workspace.

What do I need to do to get through the authentication? Do I need any further headers or options on my Invoke-WebRequest call?


Solution

  • The issue is probably because the audience of the token isn't set to management.azure.com, the resource you want to have access to.

    If you try out this command:

     az account get-access-token --resource=https://management.azure.com --query accessToken --output tsv
    

    You'll end up with a token which looks like this:

    {
      "aud": "https://management.azure.com",
      "iss": "https://sts.windows.net/[guid]/",
      "iat": 1646746056,
      "nbf": 1646746056,
      "exp": 1646750582,
      "acr": "1",
      "aio": 
    

    You can copy the complete token to jwt.io/jwt.ms to see the values of all claims.

    This token is meant for the management API, so will probably work.