Forum Discussion

rpps's avatar
rpps
New Member
1 year ago

Embedding Power BI report using service principal

Hi,

 

I'm working on embedding a power bi report  in a simple html page, but i'm running into issues while embedding the report.

 

Steps I have done:

1. Created an app in azure and povided delegated api permissions Report.Read.All, Dataset.ReadWrite.All and granted admin consent. As the html page is my desktop added redirect url as https://localhost. Then ceated an security group under the created azure app.

2. In power bi service tenant setting, enabled the api permissions by adding the security group.

3. Using postman, I have generated access token.

              Method: GET

              URL: https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token

              Under authorization: Provided Auth URL, Access Token URL, Client ID, Client secret, Scope: https://api.powerbi.com/.default.

I'm able to generate access token.

4. Added the security group and service principal to the workspace which contains the report. The workspace is a pro workspcae not premium.

 

HTML Code used:

<script src="https://cdn.jsdelivr.net/npm/powerbi-client/dist/powerbi.min.js"></script>
<script>
var models = window["powerbi-client"].models;
var embedConfig = {
type: 'report',
tokenType: models.TokenType.Embed,
accessToken: 'generated access token', // Using the token generated from Postman
embedUrl: 'https://app.powerbi.com/reportEmbed?reportId=report_id&groupId=grou_id',
id: 'report_id',
permissions: models.Permissions.All,
settings: {
filterPaneEnabled: true,
navContentPaneEnabled: true
}
};
var reportContainer = document.getElementById('reportContainer');
var report = powerbi.embed(reportContainer, embedConfig);
</script>

 

Issue: when I try to embed, I'm getting 403 () error. Access to api.powerbi.com is denied.

 

Could anyone please help on this issue

 

Thanks.

3 Replies

  • Anonymous's avatar
    Anonymous
    Not applicable

    Hi, rpps 
    Thanks for reaching out to the Microsoft fabric community forum.

    Regarding the issue you raised, my solution is as follows:

    1.First, please ensure that your access token is generated as an embedded token through the following API:


    In my tests, using the access token directly from Postman results in the following error:

    2. Secondly, check if your service settings are enabled:

    3. Then, check if the workspace role assigned to your service principal is at least a member:

     


    4.Next, here are some similar issues that might be helpful to you:
    Solved: Power BI REST API, HTTP 401 - Microsoft Fabric Community

    Solved: Getting Operation returned an invalid status code ... - Microsoft Fabric Community


    5.You can also refer to my embedding code:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Power BI Embedded Report</title>
        <!-- Import Power BI Client Library -->
        <script src="https://npmcdn.com/[email protected]/dist/powerbi.min.js"></script>
        <!-- Import jQuery -->
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <style>
            #embedContainer {
                width: 100%;
                height: 600px;
                margin: 0 auto;
            }
        </style>
    </head>
    <body>
        <div id="embedContainer"></div>
        <script>
            // Initialize Promise controls
            let loadedResolve, reportLoaded = new Promise((res, rej) => { loadedResolve = res; });
            let renderedResolve, reportRendered = new Promise((res, rej) => { renderedResolve = res; });
            // Get model references
            let models = window['powerbi-client'].models;
            let report; // Declare report variable
            // Function to embed the report
            async function embedPowerBIReport() {
               
                const accessToken = "  ";
                const embedUrl = " ";
                const embedReportId = " ";
                const tokenType = "1";
                // Configuration parameters
                const config = {
                    type: 'report',
                    tokenType: tokenType === '0' ? models.TokenType.Aad : models.TokenType.Embed,
                    accessToken: accessToken,
                    embedUrl: embedUrl,
                    id: embedReportId,
                    permissions: models.Permissions.All,
                    settings: {
                        panes: {
                            filters: { visible: true },
                            pageNavigation: { visible: true }
                        },
                        bars: {
                            statusBar: { visible: true }
                        }
                    }
                };
                // Get container element
                const embedContainer = document.getElementById('embedContainer');
                try {
                    // Embed the report
                    report = powerbi.embed(embedContainer, config);
                    // Event handlers
                    report.on("loaded", () => {
                        console.log("Report loaded");
                        loadedResolve();
                        report.off("loaded");
                    });
                    report.on("rendered", () => {
                        console.log("Report rendered");
                        renderedResolve();
                        report.off("rendered");
                    });
                    report.on("error", error => {
                        console.error("Report error:", error.detail);
                    });
                } catch (error) {
                    console.error("Embedding failed:", error);
                }
            }
            // Execute after page load
            $(document).ready(async function() {
                await embedPowerBIReport();
                await reportLoaded;
                console.log("Add post-load code here");
                
                await reportRendered;
                console.log("Add post-render code here");
            });
        </script>
    </body>
    </html>
    

    6.Here is my final result: 

    Of course, if you have any new discoveries or questions, please feel free to get in touch with us.
     

    Best Regards,

    Leroy Lu

    If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.

     

     

    • rpps's avatar
      rpps
      New Member

      Hi, Thanks your reply.

       

      I have added all the steps which you have mentioned. After generating access token from postman I have tested it using in jwt.ms.

      The aud of the access token displayed as "00000002-0000-0000-c000-000000000000" seems like the generated access token is for microsoft graph and not for power BI API. 

       

      Could you please help on generating access token for power BI API using postman.

       

      Thanks

  • rpps's avatar
    rpps
    New Member

    Hi, Thanks for your reply.

    I have done all the steps which you have mentioned.
    After generating access token i have tested it in jwt.ms. The aud for generated access toke is displayed aa "00000002-0000-0000-000000000000".
    Seems like the generated access token is for microsoft graph and not for power bi API.

    Could you please help on generating access token for power bi api.