-
-
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"; |
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?
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.
Is there any other latest way to get the access token via power BI Rest api please
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.
I am using Javascript MSAL library. Kindly advise
Hi ragavanrajan: Please refer below link:
https://github.com/tushar1up1/Powerbi-JavaScript-REST_API
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 ?
@ramandeep-singh-1983 @selmantayyar can you please give me the link for JAVA REST API if you have already found it ?
I found this URL : https://docs.microsoft.com/en-us/rest/api/power-bi/embed-token/generate-token#generate-an-embed-token-expiring-in-10-minutes
@rrohitesh sorry I don't have access to it anymore.
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.