Forum Discussion
Obtain Access Token C# App Owns Data Error
- 9 years ago
Anonymous
For App Owns data scenario, register a Native application instead. Then everything shall work.
The reason I was getting the 403 Forbidden was because I was actually getting a token, but it was the wrong token. I was getting it the wrong way. Once I switched to doing it like below, with the app registered as a Native Client, all worked great.
// Create a user password cradentials.
var credential = new UserCredential(Username, Password);
// Authenticate using created credentials
var authenticationContext = new AuthenticationContext(AuthorityUrl);
var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ClientId2, credential);
token = authenticationResult.AccessToken;
var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");
Thanks for all your help.
Stizz001
I should have PAID ATTENTION to 'register a Native AAD app' everything works well after I did that (after setting the app permissions on Azure Portal).
But note to Power BI Team - IMHO, that's a bit confusing. 'Native' as we defined it, are those running on Android, iOS, ... My C# code running on a backend service, I don't call it 'Native'
Anyway.
For those still struggling, pulling their hairs out (if you still have some, save them)...
To get that Embed Token - this piece of code works for me now
var embedToken = "";
var ClientId = "your-client-id-here-generated-when-after-you-registered-a-native-app";
var credential = new UserPasswordCredential("AADUserNameHere", "ADDUserPasswordHere");
var groupId = "Your-App-Workspace-GroupId-Here";
var reportId = "Your-ReportId-Here";
// Authenticate using created credentials
var authenticationContext = new AuthenticationContext("https://login.windows.net/common/oauth2/authorize/");
var authenticationResult = authenticationContext.AcquireTokenAsync("https://analysis.windows.net/powerbi/api", ClientId, credential).Result;
if (authenticationResult != null)
{
var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");
// Create a Power BI Client object. It will be used to call Power BI APIs.
using (var client = new PowerBIClient(new Uri("https://api.powerbi.com/"), tokenCredentials))
{
// Generate Embed Token.
var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
var tokenResponse = client.Reports.GenerateTokenInGroup(groupId, reportId, generateTokenRequestParameters);
if (tokenResponse == null)
{
throw new Exception("No token response");
}
embedToken = tokenResponse.Token;
}
}