Search code examples
c#azureresthttp-headersazure-batch

How to get list of Azure Batch Pools and Jobs using REST API in C#?


Using REST API I want to get the list of Batch Pools and Jobs.
As per the docs:
Pool - Get | Microsoft Docs - https://learn.microsoft.com/en-us/rest/api/batchservice/pool/get
Job - Get | Microsoft Docs - https://learn.microsoft.com/en-us/rest/api/batchservice/job/get

The API to get list of job is GET {batchUrl}/jobs?api-version=2019-08-01.10.0 and to get pool is GET {batchUrl}/pools?api-version=2019-08-01.10.0
In C# I am doing it like this:

client.DefaultRequestHeaders.Add("Authorization", "Bearer " + _accessToken);
using (var responseGet = client.GetAsync(api).Result) //HttpClient client
{
    if (responseGet.IsSuccessStatusCode)
    {
        dynamic batchObjectsContent = JObject.Parse(responseGet.Content.ReadAsStringAsync().Result);
        foreach (var batchObject in batchObjectsContent.value)
        {
            batchObjects.Add(new BatchObject { Id = batchObject.id, Url = batchObject.url, CreationTime = batchObject.creationTime, StateTransitionTime = batchObject.stateTransitionTime });
        }
    }
}

The complete API for getting the pool is https://mybatch.westus2.batch.azure.com/pools?api-version=2019-08-01.10.0 and api for the job is https://mybatch.westus2.batch.azure.com/jobs?api-version=2019-08-01.10.0.

Error message I am getting:
StatusCode=Unauthorized
ReasonPhrase="Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly."
error="invalid_audience", error_description="The access token has been obtained from wrong audience or resource 'https://management.azure.com/'. It should exactly match (including forward slash) with one of the allowed audiences 'https://batch.core.windows.net/'"

And this is how I got the access token: authenticationContext.AcquireTokenAsync("https://management.azure.com/", credential).Result.AccessToken;. This works for all the APIs related to https://management.azure.com/.

From the errors I think there is issue with either the access token or the headers are wrong, or both. How do I correct them ?


Solution

  • Use the Azure Batch resource endpoint to acquire a token for authenticating requests to the Batch service:

    https://batch.core.windows.net/
    

    Use the code as below:

    private const string BatchResourceUri = "https://batch.core.windows.net/";
    AuthenticationResult authResult = await authContext.AcquireTokenAsync(BatchResourceUri, new ClientCredential(ClientId, ClientKey));
    

    Refer to this article.