kakaji
kakaji

Reputation: 191

Get Azure consumption and reservation usage data using API Unable to authenticate

I am trying to authenticate this API.

Document link :

https://learn.microsoft.com/en-us/azure/cost-management-billing/reservations/charge-back-usage#get-azure-consumption-and-reservation-usage-data-using-api

API_1: https://management.azure.com/providers/Microsoft.Billing/billingAccounts/{enrollmentId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodId}/providers/Microsoft.Consumption/usagedetails?metric={metric}&api-version=2019-05-01&$filter={filter}

But I am getting this error:

{'error': {'code': '401', 'message': 'No claims present for the caller in the system'}}

But when I am trying to access this API:

https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/providers/Microsoft.Consumption/usageDetails?api-version=2021-10-01&metric=amortizedcost

I am able to access using same credentials(SPN) .

above API documentation :

https://learn.microsoft.com/en-us/rest/api/consumption/usage-details/list#usagedetailslistbymetricamortizedcost-legacy

Can anyone help me why I am unable to authenticate API_1 using same SPN.

using this code.

authentication_endpoint = 'https://login.microsoftonline.com/'
resource  = 'https://management.core.windows.net/'

# get an Azure access token using the adal library
context = adal.AuthenticationContext(authentication_endpoint + tenant_id)
token_response = context.acquire_token_with_client_credentials(resource, application_id, application_secret)
endpoint = "API_Link1"

access_token = token_response.get('accessToken')
headers = {"Authorization": 'Bearer ' + access_token}
json_output = requests.get(endpoint,headers=headers).json()
print(json_output)

Can anyone help me what mistake I am doing?

Upvotes: 0

Views: 2156

Answers (2)

learningtocode
learningtocode

Reputation: 39

To get data at enrollment level or billing account level you need to billing reader role in you service principle.

Upvotes: 0

Rukmini
Rukmini

Reputation: 15659

I tried to reproduce the same in my environment and I am able to access the second API you have given:

image1

But for the first API error: python {'error': {'code': '401', 'message': 'No claims present for the caller in the system'}} I believe that the reason is role claims are missing in the access token.

The roles are only issued in the access token when we request it using the client credentials flow which contains the permission that require admin consent.

I guess you need to check the required permissions granted on your SPN to access the API.

Upvotes: 1

Related Questions