Forum Discussion

VSmart's avatar
VSmart
Frequent Visitor
3 years ago

Get 401 Error when try to Get Activity Events (Audit Logs)

I'm trying to get Power BI audit logs using service principal.

I follow every step in creating Azure principal Embed Power BI content in an embedded analytics application with service principal and an application secret - Power BI | Microsoft Learn

1.Create app

2.Create secret 

3. Add app into group 

4. Give all permitions to app 

Tenant.Read.All, Tenant.ReadWrite.All;Report.ReadWrite.All, Report.Read.All, Dataset.Read.All;Auditlog.Read.All; Workspace.Read.All;Workspace.ReadWrite.All; and many other permitions.

5. Enable "Allow service principal to use Power BI API's" and "Enable content in apps" in Power BI admin portal.

 

I can get acces token and run few API calls like : 

My Python script is follow:

 

 

 

 

TENANT_ID = '1eb27ef3-976f-4600-a791-*******'
CLIENT_ID = 'd5376b05-a655-463b-ae9f-*******'
CLIENT_SECRET = '**************************'
SCOPE_BASE = ['https://analysis.windows.net/powerbi/api/.default']
AUTHORITY_URL = 'https://login.microsoftonline.com/organizations'
try:
    authority = AUTHORITY_URL.replace('organizations', TENANT_ID)
    clientapp = msal.ConfidentialClientApplication(CLIENT_ID, client_credential=CLIENT_SECRET, authority=authority)
    response = clientapp.acquire_token_for_client(scopes=SCOPE_BASE)
    try:
        access_token = response['access_token']
        activityDate = date.today() - timedelta(days=1)
        activityDate = activityDate.strftime("%Y-%m-%d")

        url = "https://api.powerbi.com/v1.0/myorg/admin/activityevents?startDateTime='" + activityDate + "T00:00:00'&endDateTime='" + activityDate + "T23:59:59'"
        header = {'Content-Type':'application/json', 'Authorization':f'Bearer {access_token}'}
        api_call = requests.get(url=url, headers=header)
        print(api_call)
        print(api_call.json())

    except KeyError:
        raise Exception(response['error_description'])

except Exception as ex:
    raise Exception('Error retrieving Access token\n' + str(ex))

 

 

 

 

 

 

4 Replies