Refresh the access token

Embedding and interacting with Power BI reports, dashboards and tiles requires the use of 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, the time you have to interact with it is limited. In order to allow your users continuous experience, you need to refresh the access token you are using before it is expired.

Set the access token

setAccessToken can be used to update the access token without reloading the embedded report. It should be used when the token is about to be expired.

await report.setAccessToken(newAccessToken);

Refresh token example

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

Note

getNewUserAccessToken() is a function you need to implement, it calls your application back-end for generating a new embed token, or refreshes the Azure AD token.

const MINUTES_BEFORE_EXPIRATION = 10;
const INTERVAL_TIME = 4;

// 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)
    }​​​​
}​​​​);

Next steps