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

Register now to learn Fabric in free live sessions led by the best Microsoft experts. From Apr 16 to May 9, in English and Spanish.

Reply
Anonymous
Not applicable

secure embed using js sdk

Hi all, 

i have used the AZURE portal to create an app that allows me to embed pbi reports on my site using the JS sdk instead of iframes.

 

How can i use secure embed for displaying reports on my web site as i did so far with "regular i-frame embedding" so the user will first have to sign in using his microsoft account in order to watch the report?

 

Thanks!

 

11 REPLIES 11
Jayendran
Solution Sage
Solution Sage

Hi @Anonymous ,

 

Here is the link https://powerbi.microsoft.com/en-us/blog/easily-embed-secure-power-bi-reports-in-your-internal-portals-or-websites/

which you need to look.

 

Let me know if you need any help

Anonymous
Not applicable

Thank you for your reply, by unfortunately this link is not useful for me as i dont want to use iframe tags/

 

I want to use the js SDK for embedding reports on my site.... using the js SDK i want to embed secure reports on my site (user own data) that will be visible to user only after he logs in to his Microsoft account.... does anybody have code example, i really got lost with the documentation...

Anonymous
Not applicable

thank you Jayendran!

 

yet i am still confused about somthing:

 

In all sample app there is .Net code, while i want to use the js sdk for embedding my reports.

should i create app functions on my azure portal for the .net code part?

 

I have followed several tutorials for js embedding, in all of them it is the "app owns data" method.

JS on my page call a function that i created on the azure portal , so in fact every js function depends on .Net functions that run on azaure function app , as you can see on this code example:

 https://github.com/Dhruvinshah16/Power-BI-Embedded-Resources-Step-by-Step-Series/blob/master/Video%2...

this example is bad for me as user is not being asked to sign in to his microsoft accont before reports is dsiplayed to him - everybody who acces my web page, even if he is not a power bi user, can see the report.

 

 

I still dont understand how can i use simple js with the user owns data approach so:

1. I can make sure a pro power bi user is logged in \ ask him to lo in

2. Using simple js, display the user one on my reports from power bi

 

So far i have use i-frame tags but as i want to later on interact with the report (e.g allow bookmarks) i want to switch to the js embedding

Anonymous
Not applicable

Also, i have followed this toturial:

https://docs.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-javascript-spa

 

i sucsefuly managed to us js, sign in the user to his microsoft account and get a token,

but i dont find anything regarding how should i use the tiken i got and embed a power bi report using js....

Hi @Anonymous ,

 

Ok now you got the access token. You can pass the token to the PowerBI JS like below

 

var models = window['powerbi-client'].models;

var embedConfiguration = {
	type: 'report',
	id: '5dac7a4a-4452-46b3-99f6-a25915e0fe55',
	embedUrl: 'https://app.powerbi.com/reportEmbed',
	tokenType: models.TokenType.Aad,
	accessToken: 'e4...rf' 
};

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

 

Anonymous
Not applicable

1, First of all thank you for your reply, I really appreciate that!!!

 

2. I have try to include this code (powerbi.embed call) but for some reason i see an error on the console regarding the "models" variable (Uncaught TypeError: Cannot read property 'models' of undefined)

 

i also declared theses dependencies:


<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>

<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.0/js/msal.js"></script>

<script src="https://raw.githubusercontent.com/microsoft/PowerBI-JavaScript/master/dist/powerbi.js"></script>

 

 // load embed report"

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

var embedConfiguration = {
type: 'report',
id: '8977c9ed-bd54-42a2-9f0c-291cd3469755'--> the report id,
embedUrl: 'https://app.powerbi.com/reportEmbed',
tokenType: models.TokenType.Aad,
accessToken: 'bc182855-dc03-431e-8d21-ad64be2b4de2' --> the token i got from the JSON response 
};

var $reportContainer = $('#reportContainer');
console.log("$reportContainer", $reportContainer);
var report = powerbi.embed($reportContainer.get(0), embedConfiguration);
</script>
</body>
</html>

 

 

Can you tell me what have i been missing here?

 

Thanks again!

Hi @Anonymous 

 

Can you try the below solution

https://stackoverflow.com/a/49255085

 

$(document).ready(function () {

        // Get models. models contains enums that can be used.
        var models = powerbi.models; // or window.powerbi.models

        var embedConfiguration = {
            type: 'dashboard',
            id: 'dashboardID',
            embedUrl: 'https://app.powerbi.com/dashboardEmbed',
            tokenType: models.TokenType.Aad,
            accessToken: 'TokenString'
        };

        var $dashboardContainer = $('#embedContainer');
        var dashboard = powerbi.embed($dashboardContainer.get(0), embedConfiguration);
    });

 

Please don't forget to give kudo's or Thumbup for the replay which you got useful.

Anonymous
Not applicable

I'm still getting undifined, it's like the powerbi.js library is not there...

jquery.min.js:2 Uncaught ReferenceError: powerbi is not defined

 

yet in the head tag i call the script and i can see that the power bi js script loads to my page :

 

<head>
<title>Quickstart for MSAL JS</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.0/js/msal.js"></script>
<script src="https://raw.githubusercontent.com/microsoft/PowerBI-JavaScript/master/dist/powerbi.js"></script>
</head>

 

but when i try to console "powerbi" or "window['powerbi-client']" i get an undifineied error in the console...

Anonymous
Not applicable

Looks like the problem was with the powerbi.js script call,

when i downloaded the script and added it to the page directly the issue was resolved.

 

But (of curse) i am facing another issue:

 

When the powerbi.js try to embed and load the i-frame i get a "This content isn't available" error message inside the i frame.

Also the iframe element url is being set to "https://app.powerbi.com/reportEmbed?uid=l6rvc".

 

I have triple checked that i use the correct access token and report id yet still i'm not able to load the report.

I have also added the power bi js debuggind tool (https://github.com/Microsoft/PowerBI-JavaScript/wiki/Troubleshooting-and-debugging-of-embedded-parts)

 

i get this error after trying to emmbed a report using powerbi.embed() function:

code 403

error message : "LoadReportFailed"

detailedMessage: "Fail to initialize - Could not resolve cluster" 

Capture2.JPG

 

Capture.JPG
I have also change the token type from Aad to  Embed but it didnt make any different.
 
is there another way to check what am i doing wrong here?, maybe a missing setting in the azure app? (i added all the nedd permissions to my azure app)
 
 

Hi @Anonymous ,

 

Your github code is an example of app owns data and not User owns data

 

Here some of the links which help full for you

 

https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embedding-Basics#user-owns-the-data

 

I also got some reference from https://community.powerbi.com/t5/Developer/get-Access-token-using-js/td-p/350294 which helps you to implement the entier in HTML

 

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
		
       <script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.12/js/adal.min.js"></script>
	   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
			 <script>
			  window.config  = {
				  instance: 'https://login.microsoftonline.com/',
				  tenant: 'common', //COMMON OR YOUR TENANT ID

				  clientId: '49df1bc7-db68-4fb4-91c0-6d93f770d1a4', //This is your client ID
				  redirectUri: 'https://login.live.com/oauth20_desktop.srf', //This is your redirect URI

				  callback: userSignedIn,
				  popUp: true
			  };
			  
			  var ADAL = new AuthenticationContext(config);

				function signIn() {
				      ADAL.login();
				  }
				
				  function userSignedIn(err, token) {
				      console.log('userSignedIn called');
				      if (!err) {
                				          
                  showWelcomeMessage();
				  
				  ADAL.acquireToken("https://analysis.windows.net/powerbi/api", function (error, token) {

            // Handle ADAL Error
            if (error || !token) {
                printErrorMessage('ADAL Error Occurred: ' + error);
                return;
            }

            // Get TodoList Data
            $.ajax({
                type: "GET",
                url: "https://api.powerbi.com/v1.0/myorg/datasets",
                headers: {
                    'Authorization': 'Bearer ' + token,
                },
            }).done(function (data) {

               
                console.log(data);

                    

                // Update the UI
                $loading.hide();
               

            }).fail(function () {
                printErrorMessage('Error getting todo list data')
            }).always(function () {

                // Register Handlers for Buttons in Data Table
                registerDataClickHandlers();
            });
        });
				      }
				      else {
				          console.error("error: " + err);
				      }
				  }
				  
				  
				  
				  
				  function getDataSets(){
				   
						      
                  var trythis = "Bearer " + token;
    							var request = new XMLHttpRequest();

                  request.open('GET', 'https://api.powerbi.com/v1.0/myorg/datasets');
                  
                  request.setRequestHeader('Authorization', trythis);
                  
                  request.onreadystatechange = function () {
                    if (this.readyState === 4) {
                      console.log('Status:', this.status);
                      console.log('Body:', this.responseText);
                    }
                  };
                  
                  request.send();
				  
				  
				  }
				  
				  
				  
				
				  function showWelcomeMessage() {
				      var user = ADAL.getCachedUser();
				      var divWelcome = document.getElementById('WelcomeMessage');
				      divWelcome.innerHTML = "Welcome " + user.profile.name;
				  }
        </script>

    </head>
    <body>
        
        
			 <button id="SignIn" onclick="signIn()">Sign In</button>
			 <h4 id="WelcomeMessage"></h4>	
             
      
             
             
    </body>
</html>

 

Not but not lease read the official document before implementation for clear understanding

https://docs.microsoft.com/en-us/power-bi/developer/embed-sample-for-your-organization

 

Helpful resources

Announcements
Microsoft Fabric Learn Together

Microsoft Fabric Learn Together

Covering the world! 9:00-10:30 AM Sydney, 4:00-5:30 PM CET (Paris/Berlin), 7:00-8:30 PM Mexico City

PBI_APRIL_CAROUSEL1

Power BI Monthly Update - April 2024

Check out the April 2024 Power BI update to learn about new features.

April Fabric Community Update

Fabric Community Update - April 2024

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