Skip to content
Advertisement

How to auto generate embed token using javascript and PHP?

I also posted this on the PowerBI Community but haven’t gotten any traction: https://community.powerbi.com/t5/Developer/Auto-Generate-Embed-Token-using-Javascript-and-PHP/td-p/1316556

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>

Advertisement

Answer

You need to make two cURL calls to https://login.windows.net/common/oauth2/token and https://api.powerbi.com/v1.0/myorg/groups/{YourGroupID}/reports/ to generate an Embed Access Token. YourGroupID needs to be changed to the WorkspaceId you want to embed from. You also need to set the clientid, username, and password to appropriate values. The below code will set $embedUrl and $embed variables dynamically for you. There is some room for improvement around how ReportId and EmbedUrl set but this is enough to get embedding working.

/* 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',

client_id => '', // Registered App ApplicationID

username => '', // for example john.doe@yourdomain.com

password => '' // Azure password for above user

)

));

$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(

CURLOPT_URL => "https://api.powerbi.com/v1.0/myorg/groups/YourGroupID/reports/",

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.

}

Now in your javascript where you do the embedding you can pass in the ReportID, $embedUrl and $token to successfully embed the report.

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

<script src="scripts/powerbi.js"></script>

<div id="reportContainer"></div>

 

<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',

id: 'YourReportId', // the report ID

embedUrl: "<?php echo $embedUrl ?>",

accessToken: "<?php echo $token; ?>" ,

};

var $reportContainer = $('#reportContainer');

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

</script>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement