cancel
Showing results for 
Search instead for 
Did you mean: 
Reply
oflok000 Frequent Visitor
Frequent Visitor

get Access token using js

Hello

I was just wondering if it's possible to get access token using js?? If yes would be possible show me sample

var getAccessToken = function () {

    return new Promise(function (resolve, reject) {

        var url = 'https://login.microsoftonline.com/common/oauth2/token';

        var username = 'login'; // Username of PowerBI "pro" account - stored in config
        var password = 'password'; // Password of PowerBI "pro" account - stored in config
        var clientId ='id' // Applicaton ID of app registered via Azure Active Directory - stored in config

    var headers = {
            'Content-Type': 'application/x-www-form-urlencoded'
        };

        var formData = {
            grant_type: 'password',
            client_id: clientId,
            resource: 'https://analysis.windows.net/powerbi/api',
            scope: 'openid',
            username: username,
            password: password
        };

        console.log(request.post)

        request.post({
            url: url,
            form: formData,
            headers: headers

        }, function (err, result, body) {
            console.log(result);
        })
    });
}

This what I tried to make but I alsway has problem

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://login.microsoftonline.com/common/oauth2/token. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

I tried to add it on head for my post query but it's still doesnt work

1 ACCEPTED SOLUTION

Accepted Solutions
Microsoft v-ljerr-msft
Microsoft

Re: get Access token using js

Hi @oflok000,

 

Based on my research, you may need to use the ADAL.js to get the access_token in pure js code. Here is a similar thread for your reference. Smiley Happy

 

Sample Code:

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

 

Regards

View solution in original post

3 REPLIES 3
Microsoft v-ljerr-msft
Microsoft

Re: get Access token using js

Hi @oflok000,

 

Based on my research, you may need to use the ADAL.js to get the access_token in pure js code. Here is a similar thread for your reference. Smiley Happy

 

Sample Code:

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

 

Regards

View solution in original post

gmisslinwigo Frequent Visitor
Frequent Visitor

Re: get Access token using js

Hi,

 

I would like to get the accesToken of a client. 

 

I have his username, his password and the link for an emebbed report.

 

this is my link : https://app.powerbi.com/groups/me/reports/my-report-id?ctid=my-client-id

 

So with all these informations, can i get the access token so i can embed the report on my own ? 

 

I tried to use the javascript's code of "v-ljerr-msft" but it doesn't work with my clientId. 

 

I get this error : 

 

AADSTS70001: Application with identifier my-client-id was not found in the directory my-directory
 
Can someone help me ?
 
Geoffrey 
 
Highlighted
Christy Frequent Visitor
Frequent Visitor

Re: get Access token using js

I'm trying to get this flow working myself, so take my advice with a grain of salt, but it appears you have a wrong combination of tenant ID and client ID. Try using just "common" instead of the tenant ID

Helpful resources

Announcements
New Ranks and Rank Icons in 2020

New Ranks and Rank Icons in 2020

Read the announcement for more information!

New Kudos Given Badges Coming

New Kudos Given Badges Coming

We're rolling out new Kudos Given badges. Find out how many Kudos you've given.

November 2019 Community Highlights

November 2019 Community Highlights

Get an overview of the events and great community content from November.

Power Platform World Tour

Power Platform World Tour

Find out where you can attend!

Top Solution Authors
Top Kudoed Authors (Last 30 Days)