I have been going crazy trying to pull activity logs from the Power BI Rest API. I can do it using this "try it" method from Microsoft https://learn.microsoft.com/en-us/rest/api/power-bi/admin/getactivityevents
I have to login to use this tool and then I get a bearer JWT token that is valid for 1 hour, and can be used in the header of subsequent get requests inside scripts. However the token expires after 1 hour, and I have to relogin to get a new token and update my script. I'm trying to retrieve a JWT token every time it expires without having to login via a GUI. This is to basically automate getting logs from Power BI to send to a security application for analysis. On the Azure/Power BI side, I have registered a Native app using this link https://dev.powerbi.com/Apps. On the Azure app registrations I have given the app all API permissions.
I have some sample python code using the adal library that I'm trying to get working here.Powershell solutions would also be acceptable I guess, but I prefer using python.
import adal
import requests
import json
import pandas
authority_url = 'https://login.windows.net/common'
resource_url = 'https://analysis.windows.net/powerbi/api'
client_id = 'my client ID'
client_secret = 'my client secret'
context = adal.AuthenticationContext(authority=authority_url,
validate_authority=True,
api_version=None)
# get JWT access token without having to log in
token = context.acquire_token_with_client_credentials(resource_url, client_id, client_secret)
access_token = token.get('accessToken')
logs_request_url = "https://api.powerbi.com/v1.0/myorg/admin/activityevents?startDateTime=%272021-02-20T00%3A00%3A00.000Z%27&endDateTime=%272021-02-20T23%3A59%3A59.000Z%27"
header = {'Authorization': f'Bearer {access_token}','Content-Type': 'application/json'}
response = requests.get(url=logs_request_url, headers=header).content
logs_request = json.loads(response)
# Power BI Activity Logs
print(logs_request)
This code gets me an empty response. If I paste the access_token generated when I logged in using the "try it" tool, it works. I'm trying to avoid manually logging in if possible, because this script would run as a scheduled task. I would appreciate any assistance on this, as I'm going crazy trying to get this to work.