Refresh the access token

Embedding and interacting with Power BI content (reports, dashboards and tiles) requires an access token. The access token can be either an Azure AD token, when embedding for your organization, or an embed token, when embedding for your customers. The access token has an expiration time, which means that after embedding a Power BI item, you have a limited amount of time to interact with it. To give your users a continuous experience, refresh (or renew) the access token before it expires.

There are two ways to refresh your access token:

  • Directly using the setAccessToken API
  • Automatically if you're using an Azure AD token for embed for your organization

Refresh the access token directly

setAccessToken can be used to update the access token without reloading the embedded report. Use it when the token is about expire.

await report.setAccessToken(newAccessToken);

Manual token refresh example

To refresh your access token manually, implement getNewUserAccessToken(). This function calls your application backend to generate a new embed token, or refreshes the Azure AD token.

Below is an example of how to manually implement the getNewUserAccessToken() function to refresh your access token before it expires.

const MINUTES_BEFORE_EXPIRATION = 10;

// Set the refresh interval time to 30 seconds
const INTERVAL_TIME = 30000;

// Get the token expiration from the access token
var tokenExpiration;

// Set an interval to check the access token expiration, and update if needed
setInterval(() => checkTokenAndUpdate(reportId, groupId), INTERVAL_TIME);

function checkTokenAndUpdate(reportId, groupId) {
    // Get the current time
    const currentTime = Date.now();
    const expiration = Date.parse(tokenExpiration);

    // Time until token expiration in milliseconds
    const timeUntilExpiration = expiration - currentTime;
    const timeToUpdate = MINUTES_BEFORE_EXPIRATION * 60 * 1000;

    // Update the token if it is about to expired
    if (timeUntilExpiration <= timeToUpdate)
    {
        console.log("Updating report access token");
        updateToken(reportId, groupId);
    }
}

async function updateToken(reportId, groupId) {
    // Generate a new embed token or refresh the user Azure AD access token
    let newAccessToken = await getNewUserAccessToken(reportId, groupId);

    // Update the new token expiration time
    tokenExpiration = newAccessToken.expiration;

    // Get a reference to the embedded report HTML element
    let embedContainer = $('#embedContainer')[0];

    // Get a reference to the embedded report.
    let report = powerbi.get(embedContainer);

    // Set the new access token
    await report.setAccessToken(newAccessToken.token);
}

// Add a listener to make sure token is updated after tab was inactive
document.addEventListener("visibilitychange", function() {​​​​
    // Check the access token when the tab is visible
    if (!document.hidden) {​​​​
        checkTokenAndUpdate(reportId, groupId)
    }​​​​
}​​​​);

Automatically refresh token

If you're using an Azure AD token for the embed for your organization scenario, you can refresh the access token automatically by setting an event hook in your embedding configuration parameters. The event hook will call a function that generates new tokens and assign the generated token to the embedded item before the current token expires. All you need to do is provide the token generating function, and the rest happens automatically.

Note

Refreshing the access token automatically is supported from powerbi-client JavaScript library version 2.20.1.

To refresh the access token automatically, set the accessTokenProvider function as a parameter in IEmbedConfiguration when embedding. This function is implemented by the customer and returns a fresh token when it's called. When the token is close to expiring, the iframe will call the accesTokenProvider hook to acquire a new token from the hosting app, and then set the new token.

Automatically refresh token example

Below is an example of how to automatically refresh your access token before it expires.

let getNewAccessToken = async function () {
        // Code you need to add for generating new Azure AD token
        return token;
    };

let config = {
        type: 'report',
        tokenType: models.TokenType.Aad,
        accessToken: “eyJ0 …”,
        embedUrl: “https: …”,
        eventHooks: {
            accessTokenProvider: getNewAccessToken
        }
    };

// Get a reference to the embedded report HTML element
let embedContainer = $('#embedContainer')[0];

// Embed the report and display it within the div container.
report = powerbi.embed(embedContainer, config);

Considerations and limitations

  • Automatically refreshing the access token is only supported for the embed for your organization (user owns data) scenario.
  • The accessTokenProvider event hook should never throw an exception. If it fails to generate a new token, return a Null value.

Next steps

Understanding the different embedding solutions