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

Register now to learn Fabric in free live sessions led by the best Microsoft experts. From Apr 16 to May 9, in English and Spanish.

Reply
govardhanams
Regular Visitor

Generate Embed Token using Service Principle Account

Hi Team, 

 

I already have done all this steps:

  1. I have my Tenant account properly setup in Azure - Done
  2. Allow Service Principal to use the API Services. - Done
  3. Add Tenant account to the Security groups with all privilages to read and write.-  Done
  4. Add the Account to the Workspace as an Admin. - Done

I was successfully able to authenticate with powerbi client and get the Token Using PowerBI Rest API i was able to get the list of reports in the Workspa,but when I try to get the report (client.Reports.GenerateTokenInGroupAsync) I got the next error: "

Operation returned an invalid status code 'Forbidden'"
 
Below is my code Snippet:
To authenticate to Power BI using SPN 

public PowerBIClient GetPowerBIClient(PowerBiSettings powerBiSettings)
{

Console.WriteLine("Creating an instance of the Client App with the Client Secret.");
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder
.Create(powerBiSettings.PowerBIClientId.ToString())
.WithClientSecret(powerBiSettings.PowerBIClientSecret)
.WithAuthority(new Uri($"https://login.microsoftonline.com/{powerBiSettings.PowerBIAppTenantId.ToString()}"))
.Build();

// Use .default to get all the permissions available (those configured in AAD for this app)
string[] scopes = new string[] { $"{powerBiSettings.ResourceUrl}/.default" };

Microsoft.Identity.Client.AuthenticationResult result = null;
try
{
Console.WriteLine("Aquiring the bearer token using the Client App");
result = app.AcquireTokenForClient(scopes).ExecuteAsync().Result;
}
catch (MsalUiRequiredException ex)
{
// The application doesn't have sufficient permissions.
// - Did you declare enough app permissions during app creation?
// - Did the tenant admin grant permissions to the application?
Console.WriteLine("Exception - MsalUiRequired: " + ex.Message);
}
catch (MsalServiceException ex) when (ex.Message.Contains("AADSTS70011"))
{
// Invalid scope. The scope has to be in the form "https://resourceurl/.default"
// Mitigation: Change the scope to be as expected.
Console.WriteLine("Exception - MsalService: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}

Console.WriteLine($"Obtained App-Only Access Token:\n{result.AccessToken}\n");
var tokenCredentials = new TokenCredentials(result.AccessToken, "Bearer");

Console.WriteLine("Creating the new Power BU client using the new bearer token.");
var _powerBIClient = new PowerBIClient(new Uri(powerBiSettings.ApiUrl), tokenCredentials);

return _powerBIClient;
}

 

To Generate the Embed Token : 

var reports = client.Reports.GetReportsInGroupAsync(powerBiUserAccess.WorkspaceId).Result;

Microsoft.PowerBI.Api.V2.Models.Report report = null;
if (!string.IsNullOrEmpty(reportId))
{
report = reports.Value.FirstOrDefault(r => r.Id == reportId);
if (report == null)
{
_logger.Error("No report found matching the ID provided. ReportId: {0}", reportId);
throw new IdInvalidException("No report found matching the ID provided.");
}
}
else
{
_logger.Error("No report ID provided.");
throw new IdMissingException("No report ID provided.");
}

GenerateTokenRequest generateTokenRequestParameters;

string accessLevel = Constants.PowerBiEmbeddedAccessType.View;
if (!string.IsNullOrEmpty(powerBiUserAccess.AccessLevel)
&& powerBiUserAccess.AccessLevel.ToLower() == Constants.TenantAccessRoles.Contributor)
{
accessLevel = Constants.PowerBiEmbeddedAccessType.View;
}

_logger.Trace("Generate Embed Token for Reports");
// Generate Embed Token for reports without effective identities.
generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: accessLevel);

EmbedToken tokenResponse = null;
try
{
_logger.Trace("Generate token in group.");
tokenResponse = client.Reports.GenerateTokenInGroup(powerBiUserAccess.WorkspaceId, report.Id, generateTokenRequestParameters);
}

 

After sometime, we are facing the below issue when Embed toke is being generated.

govardhanams_0-1606390129085.png

 

Please do the needful.

 

Thanks,

Swathi

 
1 REPLY 1
v-eqin-msft
Community Support
Community Support

Hi @govardhanams ,

 

Please try to select all the permission for PowerBI service...Or you could take a look at these for reference.

 

https://community.powerbi.com/t5/Developer/Generate-PowerBI-Embed-Token-gives-me-Forbidden-500-Inter...

https://community.powerbi.com/t5/Developer/Operation-returned-an-invalid-status-code-Forbidden/m-p/3...

https://community.powerbi.com/t5/Developer/Power-BI-Embedded-RLS-How-do-I-get-it-to-work/m-p/240359

 

Did I answer your question ? Please mark my reply as solution. Thank you very much.

 

Best Regards,
Eyelyn Qin

Helpful resources

Announcements
Microsoft Fabric Learn Together

Microsoft Fabric Learn Together

Covering the world! 9:00-10:30 AM Sydney, 4:00-5:30 PM CET (Paris/Berlin), 7:00-8:30 PM Mexico City

PBI_APRIL_CAROUSEL1

Power BI Monthly Update - April 2024

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

April Fabric Community Update

Fabric Community Update - April 2024

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

Top Solution Authors
Top Kudoed Authors