This example shows how to get an access token for a Power BI client application when using the Client Credentials grant type.
The Client Credentials grant type is typically used for building a backend service or automated flow. For example, the Client Credentials grant type allows a dashboard to be automatically updated without relying on user authentication, which breaks if the client credentials are changed.
Required information
-
The information supplied by the identity provider upon registering Power BI as a client application:
-
Token URL
-
Client ID
-
Client Secret
-
Scope
-
State (optional)
-
For the Smart Cloud environment, this information is supplied by the Smart Cloud support team when they respond to the request to register Postman as a client.
-
For other environments, you can get the Token, Issuer, and Authorization URLs from the configuration endpoint for your identity provider:
<idp_hostname>/<idp_baseurl>/.well-known/openid-configuration
-
Create a query to get an access token
Be extremely cautious about sharing any PBIX template created! The credentials stored in the token function will allow anyone access to your company's data, and that access might not be limited to data stored in Smart Completions.
-
In the Power BI desktop tool create a blank query.
-
Right-click the query, and select Advance Editor.
-
Copy and paste the following code into the blank query:
()=>let
// Set the client ID and client secret
client_id = "xxxxx",
client_secret = "xxxxx",
// Set the OAuth2 token endpoint
token_endpoint = "https://<idp_hostname>/v1/token",
// Set the HTTP headers for the token request
token_headers = [
#"Content-Type" = "application/x-www-form-urlencoded",
#"Accept" = "application/json"
],
// Set the token request body
token_body = "grant_type=client_credentials&client_id=" &
client_id & "&client_secret=" & client_secret & "&scope= xxxxx " ,
// Request an access token from the OAuth2 server
token_response = Json.Document(Web.Contents(token_endpoint,
[Headers = token_headers, Content = Text.ToBinary(token_body)])),
access_token = token_response[access_token]
in
access_token
-
Replace the values for client_id, client_secret, token_endpoint, and scope with your information.
-
Change the query name to GetToken and click Done.
Use the query to get the access token
-
Create a second blank query for getting the token using the above GetToken function.
-
Copy and paste the following code into the blank query:
let
Source = OData.Feed("https://<hostname>/sc/datalake/v1",[Authorization="Bearer "&GetToken()],[MoreColumns=true])
in
Source
-
Replace the <hostname> placeholder with your hostname.
-
Click Done.
The query automatically generates a token and loads the data.