Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

Earn the coveted Fabric Analytics Engineer certification. 100% off your exam for a limited time only!

Reply
Noobtastic_com
Regular Visitor

Auto Generate Embed Token using Javascript and PHP

I have gotten my report working in test with a token generated using the Microsoft Embed Token - Generate Token (here https://docs.microsoft.com/en-us/rest/api/power-bi/embedtoken/generatetoken) and by using the PowerShell commands.

I got the formatting just right, changed some config and got it all working just how I wanted it on localhost.

To try figuring it out, I also used the automated Embedded setup via powerbi.com (here https://app.powerbi.com/embedsetup/appownsdata). I played around with the downloaded vs files which shows that generating the token on the fly is possible but it is all ASP.net and C# and I can't figure out how to convert it.

Now I am trying to get it deployed to production into my site which uses PHP and javascript.

Does anyone have some samples or anything where I could swap out my ReportId, GroupId, etc? Script kiddie style...

Here is what I am using that works perfectly, except for the expiring manually generated token:

 

<script src="./dist/powerbi.js"></script>
<div id="reportContainer" style="height: 1400px; width: 1000px;"></div>

  <script>
      // Get models. models contains enums that can be used.
      var models = window['powerbi-client'].models;

      // Embed configuration used to describe what and how to embed.
      // This object is used when calling powerbi.embed.
      // This also includes settings and options such as filters.
      // You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.
      var embedConfiguration = {
          type: 'report',
          tokenType: models.TokenType.Embed,
          accessToken: '<manually generated token here>',
          embedUrl: 'https://app.powerbi.com/reportEmbed',
          id: '<report id here>',
          permissions: models.Permissions.Read,
          settings: {
              // filterPaneEnabled: false,
              // navContentPaneEnabled: true,
              background: models.BackgroundType.Transparent,
              panes:{
                bookmarks: {
                  visible: false
                },
                fields: {
                  expanded: false
                },
                filters: {
                  expanded: false,
                  visible: false
                },
                pageNavigation: {
                  visible: true
                },
                selection: {
                  visible: false
                },
                syncSlicers: {
                  visible: false
                },
                visualizations: {
                  expanded: false
                }
              }

          }
      };

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

      // Embed the report and display it within the div container.
      var report = powerbi.embed($reportContainer, embedConfiguration);
  </script>

 

 

1 ACCEPTED SOLUTION
Noobtastic_com
Regular Visitor

I got the answer over on Stack Overflow: https://stackoverflow.com/questions/63564271/how-to-auto-generate-embed-token-using-javascript-and-p...

For anyone else, below is the working code with the formatting that I used. It should be mostly plug and play after changing 5 values to those applicable to your report.

Note that I couldn't get it to work on localhost due errors that appeared to be related to an authentication issue between localhost and the PowerBI servers. It does work on the live site.

Feel free to make it your own. Hopefully it will work with very minimal changes required.

<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="./dist/powerbi.js"></script>

<div id="reportContainer" style="height: 1400px; width: 1000px;"></div>

<?php
    // All the values used below can be generated at https://app.powerbi.com/embedsetup/appownsdata
    
    /* Get oauth2 token using a POST request */
    $curlPostToken = curl_init();
    curl_setopt_array($curlPostToken, array(
        CURLOPT_URL => "https://login.windows.net/common/oauth2/token",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => array(
            grant_type => 'password',
            scope => 'openid',
            resource => 'https://analysis.windows.net/powerbi/api',
            
            // Make changes Start
            client_id => '#####################', // Registered App Application ID
            username => 'john.doe@yourdomain.com', // for example john.doe@yourdomain.com
            password => '#####################', // Azure password for above user
            // Make changes End
        )
    ));

    $tokenResponse = curl_exec($curlPostToken);
    $tokenError = curl_error($curlPostToken);
    curl_close($curlPostToken);

    // decode result, and store the access_token in $embeddedToken variable:
    $tokenResult = json_decode($tokenResponse, true);
    $token = $tokenResult["access_token"];
    $embeddedToken = "Bearer "  . ' ' .  $token;

    /* Use the token to get an embedded URL using a GET request */
    $curlGetUrl = curl_init();
    curl_setopt_array($curlGetUrl, array(
        
        // Make changes Start
        CURLOPT_URL => "https://api.powerbi.com/v1.0/myorg/groups/#####################/reports/", // Enter your Workspace ID, aka Group ID
        // Make changes End
        
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_HTTPHEADER => array(
            "Authorization: $embeddedToken",
            "Cache-Control: no-cache",
        ),
    ));

    $embedResponse = curl_exec($curlGetUrl);
    $embedError = curl_error($curlGetUrl);
    curl_close($$curlGetUrl);
    if ($embedError) {
        echo "cURL Error #:" . $embedError;
        } else {
            $embedResponse = json_decode($embedResponse, true);
            $embedUrl = $embedResponse['value'][0]['embedUrl']; // this is just taking the first value. you need logic to find the report you actually want to embed. This EmbedUrl needs to match the corresponding ReportId you later use in the JavaScript.
        }
?>



<script>
    // Get models. models contains enums that can be used.
    var models = window['powerbi-client'].models;

    // Embed configuration used to describe the what and how to embed.
    // This object is used when calling powerbi.embed.
    // This also includes settings and options such as filters.
    // You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.

    var embedConfiguration= {
        type: 'report',
        
        // Make changes Start
        id: '#####################', // the report ID
        // Make changes End
        
        embedUrl: "<?php echo $embedUrl ?>",
        accessToken: "<?php echo $token; ?>",
        permissions: models.Permissions.Read,
        settings: {
            background: models.BackgroundType.Transparent,
            panes:{
                bookmarks: {
                    visible: false
                },
                fields: {
                    expanded: false
                },
                filters: {
                    expanded: false,
                    visible: false
                },
                pageNavigation: {
                    visible: false
                },
                selection: {
                    visible: false
                },
                syncSlicers: {
                    visible: false
                },
                visualizations: {
                    expanded: false
                }
            }
        }
    };

    var $reportContainer = $('#reportContainer');
    var report = powerbi.embed($reportContainer.get(0), embedConfiguration);

</script>

 

View solution in original post

3 REPLIES 3
Noobtastic_com
Regular Visitor

I got the answer over on Stack Overflow: https://stackoverflow.com/questions/63564271/how-to-auto-generate-embed-token-using-javascript-and-p...

For anyone else, below is the working code with the formatting that I used. It should be mostly plug and play after changing 5 values to those applicable to your report.

Note that I couldn't get it to work on localhost due errors that appeared to be related to an authentication issue between localhost and the PowerBI servers. It does work on the live site.

Feel free to make it your own. Hopefully it will work with very minimal changes required.

<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="./dist/powerbi.js"></script>

<div id="reportContainer" style="height: 1400px; width: 1000px;"></div>

<?php
    // All the values used below can be generated at https://app.powerbi.com/embedsetup/appownsdata
    
    /* Get oauth2 token using a POST request */
    $curlPostToken = curl_init();
    curl_setopt_array($curlPostToken, array(
        CURLOPT_URL => "https://login.windows.net/common/oauth2/token",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => array(
            grant_type => 'password',
            scope => 'openid',
            resource => 'https://analysis.windows.net/powerbi/api',
            
            // Make changes Start
            client_id => '#####################', // Registered App Application ID
            username => 'john.doe@yourdomain.com', // for example john.doe@yourdomain.com
            password => '#####################', // Azure password for above user
            // Make changes End
        )
    ));

    $tokenResponse = curl_exec($curlPostToken);
    $tokenError = curl_error($curlPostToken);
    curl_close($curlPostToken);

    // decode result, and store the access_token in $embeddedToken variable:
    $tokenResult = json_decode($tokenResponse, true);
    $token = $tokenResult["access_token"];
    $embeddedToken = "Bearer "  . ' ' .  $token;

    /* Use the token to get an embedded URL using a GET request */
    $curlGetUrl = curl_init();
    curl_setopt_array($curlGetUrl, array(
        
        // Make changes Start
        CURLOPT_URL => "https://api.powerbi.com/v1.0/myorg/groups/#####################/reports/", // Enter your Workspace ID, aka Group ID
        // Make changes End
        
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_HTTPHEADER => array(
            "Authorization: $embeddedToken",
            "Cache-Control: no-cache",
        ),
    ));

    $embedResponse = curl_exec($curlGetUrl);
    $embedError = curl_error($curlGetUrl);
    curl_close($$curlGetUrl);
    if ($embedError) {
        echo "cURL Error #:" . $embedError;
        } else {
            $embedResponse = json_decode($embedResponse, true);
            $embedUrl = $embedResponse['value'][0]['embedUrl']; // this is just taking the first value. you need logic to find the report you actually want to embed. This EmbedUrl needs to match the corresponding ReportId you later use in the JavaScript.
        }
?>



<script>
    // Get models. models contains enums that can be used.
    var models = window['powerbi-client'].models;

    // Embed configuration used to describe the what and how to embed.
    // This object is used when calling powerbi.embed.
    // This also includes settings and options such as filters.
    // You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.

    var embedConfiguration= {
        type: 'report',
        
        // Make changes Start
        id: '#####################', // the report ID
        // Make changes End
        
        embedUrl: "<?php echo $embedUrl ?>",
        accessToken: "<?php echo $token; ?>",
        permissions: models.Permissions.Read,
        settings: {
            background: models.BackgroundType.Transparent,
            panes:{
                bookmarks: {
                    visible: false
                },
                fields: {
                    expanded: false
                },
                filters: {
                    expanded: false,
                    visible: false
                },
                pageNavigation: {
                    visible: false
                },
                selection: {
                    visible: false
                },
                syncSlicers: {
                    visible: false
                },
                visualizations: {
                    expanded: false
                }
            }
        }
    };

    var $reportContainer = $('#reportContainer');
    var report = powerbi.embed($reportContainer.get(0), embedConfiguration);

</script>

 

Noobtastic_com
Regular Visitor

I can't be the only one that has run into this.

I have seen the ones for creating a function but I can't seem to get that to work either.

Has anyone gotten this to work with PHP and javascript?

Maybe a different authentication method would be better? Not sure what other options there might be.

Hi @Noobtastic_com,

AFAIK, power bi generates token API include token string, expired time. I think you need to do add some additional processes to store and check generated tokens and the expired time. 

For example:

Add if statements to check the expired time and stored token codes into your script.
If tokens expired or did not exist, you can invoke power bi rest to generated new tokens and corresponding token lifecycles and stored to sessions.

Regards,

Xiaoxin Sheng

Community Support Team _ Xiaoxin
If this post helps, please consider accept as solution to help other members find it more quickly.

Helpful resources

Announcements
April AMA free

Microsoft Fabric AMA Livestream

Join us Tuesday, April 09, 9:00 – 10:00 AM PST for a live, expert-led Q&A session on all things Microsoft Fabric!

March Fabric Community Update

Fabric Community Update - March 2024

Find out what's new and trending in the Fabric Community.

Top Solution Authors