Skip to content

Instantly share code, notes, and snippets.

@ramandeep-singh-1983
Created September 20, 2018 05:50
Show Gist options
  • Save ramandeep-singh-1983/0350b22130884ecefdb54f41a92ba232 to your computer and use it in GitHub Desktop.
Save ramandeep-singh-1983/0350b22130884ecefdb54f41a92ba232 to your computer and use it in GitHub Desktop.
/// <summary>
/// Retrieves the access token required to access the Power BI Pro account data.
/// </summary>
/// <returns>Access token required to access Power BI reports</returns>
/// <response code="200">OK</response>
/// <response code="401">Unauthorized</response>
// GET: api/reports/accessToken
[HttpGet]
[Route("api/reports/accessToken")]
public async Task<IHttpActionResult> GetAccessToken()
{
var accessToken = await GetAccessTokenInternalAsync();
if (accessToken == "")
{
return Unauthorized();
}
return Ok(accessToken);
}
/// <summary>
/// Retrieves the access token required to access the Power BI Pro account data.
/// </summary>
/// <returns>Access token required to access Power BI reports or empty string on error.</returns>
private async Task<string> GetAccessTokenInternalAsync()
{
// Check for existing and valid access token
if (powerBiAccessToken != "" && ValidateToken(powerBiAccessToken))
{
return powerBiAccessToken;
}
// We might need to change the following code for .NET Core in near future.
// Refer https://community.powerbi.com/t5/Developer/Embed-Power-BI-dashboard-in-ASP-Net-core/m-p/284314#M8436
try
{
// Create a user password credentials.
var credential = new UserPasswordCredential(powerBiConfiguration.UserName, powerBiConfiguration.Password);
// Authenticate using created credentials
var authenticationContext = new AuthenticationContext(powerBiConfiguration.AuthorityUrl);
var authenticationResult = await authenticationContext.AcquireTokenAsync(powerBiConfiguration.ResourceUrl, powerBiConfiguration.ClientId, credential);
if (authenticationResult == null)
{
return "";
}
powerBiAccessToken = authenticationResult.AccessToken;
return authenticationResult.AccessToken;
}
catch (Exception e)
{
Console.WriteLine("Failed to fetch Power BI access token, exception details: ", e);
}
return "";
}
/// <summary>
/// Validates the given access token.
/// </summary>
/// <param name="token">Access token to be checked for validity (required)</param>
/// <returns>True if token is valid, false otherwise.</returns>
private bool ValidateToken(string token)
{
// Code reference: https://github.com/dream-365/OfficeDev-Samples/blob/master/samples/Office365DevQuickStart/OAuth2-basic/JsonWebTokenValidator.cs
bool isValid = true;
try
{
string stsDiscoveryEndpoint = "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration";
SecurityToken jwt;
ConfigurationManager<OpenIdConnectConfiguration> configManager =
new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint,
new OpenIdConnectConfigurationRetriever());
OpenIdConnectConfiguration config = configManager.GetConfigurationAsync().Result;
TokenValidationParameters validationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = false,
IssuerSigningKeys = config.SigningKeys,
ValidateLifetime = true
};
JwtSecurityTokenHandler tokendHandler = new JwtSecurityTokenHandler();
tokendHandler.ValidateToken(token, validationParameters, out jwt);
}
catch (Exception) // Token invalid/expired
{
isValid = false;
}
return isValid;
}
pbiConfig.AuthorityUrl = "https://login.windows.net/common/oauth2/authorize/";
pbiConfig.ResourceUrl = "https://analysis.windows.net/powerbi/api";
pbiConfig.ApiUrl = "https://api.powerbi.com/";
pbiConfig.ClientId = "Provide application/client ID of the app registered in Azure AD here";
pbiConfig.GroupId = "Provide Power BI workspace/group ID here";
pbiConfig.UserName = "Provide Power BI service (app.powerbi.com) user name here";
pbiConfig.Password = "Provide Power BI service (app.powerbi.com) password here";
@ramandeep-singh-1983
Copy link
Author

The Web.config is given just for reference as these values are used in PowerBiController.cs above. Ideally, the config should only contain the relevant URLs, client ID, Group ID etc. The Power BI user name and password should be stored in a secure location like Azure Key Vault.

@selmantayyar
Copy link

Thanks for the insightful code. I need to generate the access token using my own tech stack which is not .NET. (Java or Node.js)
Is it possible to get this done without using .net?

@ramandeep-singh-1983
Copy link
Author

There was a Node.js SDK but sadly it has been deprecated. You can use the REST APIs in Java or Node.js to generate the access token.

@ragavanrajan
Copy link

Is there any other latest way to get the access token via power BI Rest api please

@tushar1up1
Copy link

Is there any other latest way to get the access token via power BI Rest api please

Do you use C#/.NET or JavaScript? There are options in both.

@ragavanrajan
Copy link

I am using Javascript MSAL library. Kindly advise

@tushar1up1
Copy link

Hi ragavanrajan: Please refer below link:
https://github.com/tushar1up1/Powerbi-JavaScript-REST_API

@ranjithpanakal
Copy link

Is there any other latest way to get the access token via power BI Rest api please

Do you use C#/.NET or JavaScript? There are options in both.

Do we have link for C#.net ?

@rrohitesh
Copy link

rrohitesh commented Dec 16, 2021

@selmantayyar
Copy link

@rrohitesh sorry I don't have access to it anymore.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment