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

Get an Azure AD access token for embedding reports using JavaScript

Hi all,

I'm using the Javascript SDK of power bi in order to embbed reports on my Wrodpress website.

 

I went for the "user own data" approch as i want to use RLS .

My desiref flow is:

- user visit my site

- user being asked to log-in with his power bi account

- after use is logged in to power bi he can see the embedded report on my website.

 

I am stuck with the stage of signing in the user and getting the access token.

i was reffered to this example:

https://docs.microsoft.com/en-us/power-bi/developer/get-azuread-access-token

 

but it is being done with C#, I'm a front end developer and dont have .net environment on my server.

Does anybody have a sample or can tell me how can i do the same sample with JavaScript?,

How can i sign in the user and get an access token with JS, not C#?

 

Thank you all!

 

5 REPLIES 5
Jayendran
Solution Sage
Solution Sage

Hi @Anonymous ,

 

Here you can find the detailed code for your request.

 

<!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>

 

References:

https://community.powerbi.com/t5/Developer/get-Access-token-using-js/td-p/350294 

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

Anonymous
Not applicable

Thanks you Jayendran!

 

I have tried this code, it does get me a token but it seems like the token is not valid.

 

1. this is where i fetch the token from the script you mentioned and assign it to a variable:

ybdtoken = token;

 

function userSignedIn(err, token) {
console.log('userSignedIn called');
console.log('L35-token is: ', token);
ybdtoken = token;
if (!err) {
showWelcomeMessage();
}
else {
console.error("error: " + err);
}
}

 2. I  use it later on in the powerbi.embed() function and pass all relevent parameters, including the token i have extracted after the user prefourmed a login to his power bi account:

 

function ybdEmbed(YbdEmbeddedReportId, YbdEmbeddedReportUrl){
	// Get models. models contains enums that can be used.
var models = window['powerbi-client'].models;

console.log("models: ",models);
//console.log("out  function ybdAccessToken: ", ybdAcessToken);
//console.log("token: ",token);
var embedConfiguration = {
	type: 'report',
	id: YbdEmbeddedReportId,
	embedUrl: YbdEmbeddedReportUrl,
	tokenType: models.TokenType.Aad,
	accessToken: ybdtoken
};
console.log("embedConfiguration: ", embedConfiguration);
var $reportContainer = jQuery('#reportContainer');
console.log("$reportContainer", $reportContainer);
var report = powerbi.embed($reportContainer.get(0), embedConfiguration);
}

But for some reason it looks like the token i get is invalid:

 

when i try to embed a report using powerbi.embed() function the report i frame loads but i get an error message asking me to ask for access to this report (in power bi desktop i have already added the user to the report work space)

Capture.JPG

 

When i generate a token via GET https://api.powerbi.com/v1.0/myorg/reports:

Capture2.JPG

 

the token works fine and i can see my embedded report

 

 

any idea what can cause this?

 

thanks!!!

Anonymous
Not applicable

in general, if i use msal.js or adal.js i get a token but looks like the token is invalid as i can't access the report

Hi.. 

 

Could you find any solution to your code? I also get the same issue. 

 

When you created Azure AD App, what should be the Redirect URI? is it embed Page URL? 

 

Thank you in advance! 

Anonymous
Not applicable

Have you find solution?

 

I'm facing same issue in my application.

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.