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";
@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