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

Get certified in Microsoft Fabric—for free! For a limited time, the Microsoft Fabric Community team will be offering free DP-600 exam vouchers. Prepare now

Reply
allan_oliveira
Frequent Visitor

REST API Get Access Token

I'm new to the community and using Power BI.
I would like to make a function that updates a token every 1 hour and returns the new token inside a parameter, is it possible??
Could you help me build this function or share some example?

Thanks

1 ACCEPTED SOLUTION
v-rzhou-msft
Community Support
Community Support

Hi @allan_oliveira 

Before you use Rest API to get access token, you need to registered a client app in Azure AD. Every portal has its url to get access token. The resource url for Power BI API is "https://analysis.windows.net/powerbi/api". Then you need to add parameter into your code body, like your Client ID( from your app) or your account and password.

Here I will show you two ways to get Power BI access token.

1. Get access token by Postman.

1.png

For reference:  Solved: Power BI REST API using postman - generate embed t... - Microsoft Power BI Community

2. Try this code to get access token in visual studio by C#.

For reference: Get an authentication access token

 

using System;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace walkthrough_push_data
{
    class Program
    {
        private static string token = string.Empty;

        static void Main(string[] args)
        {

            //Get an authentication access token
            token = GetToken();

        }

        #region Get an authentication access token
        private static async Task<string> GetToken()
        {
            // TODO: Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.21.301221612
            // and add using Microsoft.IdentityModel.Clients.ActiveDirectory

            //The client id that Azure AD created when you registered your client app.
            string clientID = "{Client_ID}";

            //RedirectUri you used when you register your app.
            //For a client app, a redirect uri gives Azure AD more details on the application that it will authenticate.
            // You can use this redirect uri for your client app
            string redirectUri = "https://login.live.com/oauth20_desktop.srf";

            //Resource Uri for Power BI API
            string resourceUri = "https://analysis.windows.net/powerbi/api";

            //OAuth2 authority Uri
            string authorityUri = "https://login.microsoftonline.com/common/";

            //Get access token:
            // To call a Power BI REST operation, create an instance of AuthenticationContext and call AcquireToken
            // AuthenticationContext is part of the Active Directory Authentication Library NuGet package
            // To install the Active Directory Authentication Library NuGet package in Visual Studio,
            //  run "Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory" from the nuget Package Manager Console.

            // AcquireToken will acquire an Azure access token
            // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
            AuthenticationContext authContext = new AuthenticationContext(authorityUri);
            var token = authContext.AcquireTokenAsync(resourceUri, clientID, new Uri(redirectUri)).Result.AccessToken;

            Console.WriteLine(token);
            Console.ReadLine();

            return token;
        }

        #endregion

    }
}

 

 

Best Regards,

Rico Zhou

 

If this post helps, then please consider Accept it as the solution to help the other members find it more quickly. 

View solution in original post

11 REPLIES 11
nagarjuna120702
Microsoft Employee
Microsoft Employee

Thanks for sharing the code. My question is, the above solution is using ADAL libraries rather than MSAL for getting the token. Is it ok to use this above code for long run or will this have any impact as Microsoft is going to retire this ADAL authentication in next couple of months. Please help me if you have the code for MSAL based token acquisition. Thank you so much.

v-rzhou-msft
Community Support
Community Support

Hi @allan_oliveira 

Before you use Rest API to get access token, you need to registered a client app in Azure AD. Every portal has its url to get access token. The resource url for Power BI API is "https://analysis.windows.net/powerbi/api". Then you need to add parameter into your code body, like your Client ID( from your app) or your account and password.

Here I will show you two ways to get Power BI access token.

1. Get access token by Postman.

1.png

For reference:  Solved: Power BI REST API using postman - generate embed t... - Microsoft Power BI Community

2. Try this code to get access token in visual studio by C#.

For reference: Get an authentication access token

 

using System;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace walkthrough_push_data
{
    class Program
    {
        private static string token = string.Empty;

        static void Main(string[] args)
        {

            //Get an authentication access token
            token = GetToken();

        }

        #region Get an authentication access token
        private static async Task<string> GetToken()
        {
            // TODO: Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.21.301221612
            // and add using Microsoft.IdentityModel.Clients.ActiveDirectory

            //The client id that Azure AD created when you registered your client app.
            string clientID = "{Client_ID}";

            //RedirectUri you used when you register your app.
            //For a client app, a redirect uri gives Azure AD more details on the application that it will authenticate.
            // You can use this redirect uri for your client app
            string redirectUri = "https://login.live.com/oauth20_desktop.srf";

            //Resource Uri for Power BI API
            string resourceUri = "https://analysis.windows.net/powerbi/api";

            //OAuth2 authority Uri
            string authorityUri = "https://login.microsoftonline.com/common/";

            //Get access token:
            // To call a Power BI REST operation, create an instance of AuthenticationContext and call AcquireToken
            // AuthenticationContext is part of the Active Directory Authentication Library NuGet package
            // To install the Active Directory Authentication Library NuGet package in Visual Studio,
            //  run "Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory" from the nuget Package Manager Console.

            // AcquireToken will acquire an Azure access token
            // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
            AuthenticationContext authContext = new AuthenticationContext(authorityUri);
            var token = authContext.AcquireTokenAsync(resourceUri, clientID, new Uri(redirectUri)).Result.AccessToken;

            Console.WriteLine(token);
            Console.ReadLine();

            return token;
        }

        #endregion

    }
}

 

 

Best Regards,

Rico Zhou

 

If this post helps, then please consider Accept it as the solution to help the other members find it more quickly. 

Hi, i am trying to get access token from api, every time when api triggers it generates accesstoken, i have written code in node js, using the access token from api response, i am trying to create group in powerbi but i am getting 401 unauthorized error, i think it's related to accesstoken but when i inspect the powerbi application and i used the accesstoken then it's working,  group got created in powerbi workspace, can you help me how to get accesstoken, here is my code

async function getAccessToken() {
  const tokenEndpoint = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`; // Replace tenantId with your tenant ID or 'common'
  const params = new URLSearchParams();
  params.append("grant_type", "client_credentials");
  params.append("client_id", clientId);
  params.append("client_secret", clientSecret);

  try {
    const response = await fetch(tokenEndpoint, {
      method: "POST",
      body: params,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(`Error fetching token: ${error.error_description}`);
    }

    const data = await response.json();
    console.log("Access Token:", data.access_token);

    return data.access_token;
  } catch (error) {
    console.error("Error:", error);
  }
}response _Response [Response] {
[Symbol(realm)]: null,
[Symbol(state)]: {
aborted: false,
rangeRequested: false,
timingAllowPassed: true,
requestIncludesCredentials: true,
type: 'default',
status: 401,
timingInfo: {
startTime: 175163.28119999985,
redirectStartTime: 0,
redirectEndTime: 0,
postRedirectStartTime: 175163.28119999985,
finalServiceWorkerStartTime: 0,
finalNetworkResponseStartTime: 0,
finalNetworkRequestStartTime: 0,
endTime: 0,
encodedBodySize: 0,
decodedBodySize: 0,
finalConnectionTimingInfo: null
},
cacheState: '',
statusText: 'Unauthorized',
headersList: _HeadersList {
cookies: null,
[Symbol(headers map)]: [Map],
[Symbol(headers map sorted)]: null
},
urlList: [ [URL] ],
body: { stream: undefined }
},
[Symbol(headers)]: _HeadersList {
cookies: null,

This no longer works as the code gives out errors.

 

CS1503 Argument 2: cannot convert from 'string' to 'Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential'
CS1503 Argument 3: cannot convert from 'System.Uri' to 'Microsoft.IdentityModel.Clients.ActiveDirectory.UserAssertion'

HI, 

This url "https://analysis.windows.net/powerbi/api".  saying 

This site can’t be reached.Is this URL need to use in app registration ?pls correct me if i am wrong.

Please let me know any angular application to generae Access Token.

Thanks

Satya

Thanks for sharing the code. My question is, the above solution is using ADAL libraries rather than MSAL for getting the token. Is it ok to use this above code for long run or will this have any impact as Microsoft is going to retire this ADAL authentication in next couple of months. Please help me if you have the code for MSAL based token acquisition. Thank you so much.

Can we get a token in power bi desktop? I need to get a token from the government website API. 

Anonymous
Not applicable

hi, I use the same method and get the error message: 

"AADSTS90019: No tenant-identifying information found in either the request or implied by any provided credentials.". what should I do?

Hi @Anonymous ,

 

You need to specify your tenant_id in your URL, e.g. https://login.microsoftonline.com/{{tenant_id}}/oauth2/v2.0/token. You can find the tenant_id in the Azure Portal > Azure AD > App Registrations > YOUR_APP > Overview.

Hello how I could know application token usage in Power BI?

@v-rzhou-msft, thanks for help!

Helpful resources

Announcements
OCT PBI Update Carousel

Power BI Monthly Update - October 2024

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

September Hackathon Carousel

Microsoft Fabric & AI Learning Hackathon

Learn from experts, get hands-on experience, and win awesome prizes.

October NL Carousel

Fabric Community Update - October 2024

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

Top Solution Authors