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

The Power BI DataViz World Championships are on! With four chances to enter, you could win a spot in the LIVE Grand Finale in Las Vegas. Show off your skills.

Reply
Mexicoder
Frequent Visitor

Api report custom header add role

 

  public async Task<ActionResult> GetReportEmbedded()
        {
            // Create a user password credentials.
            var accessToken = await GetTokenCredentials();

            var tokenCredentials = new TokenCredentials(accessToken, "Bearer");

            // Generate Embed Token.

            //using (FileStream fileStream = new FileStream(powerBi.Value.pbixPath, FileMode.Open, FileAccess.Read))
            using (var client = new PowerBIClient(new Uri(powerBi.Value.ApiUrl), tokenCredentials))
            using (Task<Group> tableTalkGroup = client.Groups.GetGroupsWithHttpMessagesAsync()
                .ContinueWith(task => task.Result.Body.Value.First(group => @group.Name == "*** group name ***")))
            using (Task<Report> reportTask = client.Reports.GetReportsInGroupWithHttpMessagesAsync((await tableTalkGroup).Id).ContinueWith(task => task.Result.Body.Value.First(report => report.Name == "Power BI Template")))

            {
                Dictionary<string, List<string>> headerDictionary = new Dictionary<string, List<string>>();
                headerDictionary.Add("roles", new List<string>{ "***custom role***" });

                var tokenResponse = await client.Reports.GenerateTokenInGroupWithHttpMessagesAsync(
                    (await tableTalkGroup).Id, (await reportTask).Id, new GenerateTokenRequest(accessLevel: "view"),
                    headerDictionary, CancellationToken.None);
                // Generate Embed Configuration.
                var embedConfig = new EmbedConfig()
                {
                    EmbedToken = tokenResponse.Body,
                    EmbedUrl = (await reportTask).EmbedUrl,
                    Id = (await reportTask).Id
                };

                return View(embedConfig);
            }
        }

i have uploaded a pbix file with custom role now i am trying to apply this role to the embedded report but i don't know how to add the custom header properly to add my request for the role. the ONLY reference i could find to this is here https://docs.microsoft.com/en-ca/azure/power-bi-workspace-collections/app-token-flow 

 

but it references the deprecated "Power BI Workspace Collections". i keep seeing the customHeader Parameter in a lot of the calls i use but i don't know how to properly use it.

 

i am trying to use this for my company's multi tenant solution and i want make sure customers only have access to their data. i think im going about this in the right direction but if not please let me know.

 

 

1 ACCEPTED SOLUTION
Mexicoder
Frequent Visitor

so i still dont know how to use custom header but i figured ouut how to add roles using the GenerateTokenRequest object and the GenerateTokenInGroupWithHttpMessagesAsync call.

 

 

    private async Task<string> GetTokenCredentials()
        {
            var credential = new UserPasswordCredential(powerBi.Value.Username, powerBi.Value.Password);

            // Authenticate using created credentials
            var authenticationContext = new AuthenticationContext(powerBi.Value.AuthorityUrl);
            var authenticationResult =
                await authenticationContext.AcquireTokenAsync(powerBi.Value.ResourceUrl, powerBi.Value.ClientId,
                    credential);

            if (authenticationResult == null)
            {
                Console.WriteLine("Authentication Failed");
                return string.Empty;
            }
            return authenticationResult.AccessToken;
        }



        public async Task<ActionResult> GetReportEmbedded()
        {
            // Create a user password credentials.
            var accessToken = await GetTokenCredentials();

            var tokenCredentials = new TokenCredentials(accessToken, "Bearer");

            // Generate Embed Token.

            using (var client = new PowerBIClient(new Uri(powerBi.Value.ApiUrl), tokenCredentials))
            using (Task<Group> tableTalkGroup = client.Groups.GetGroupsWithHttpMessagesAsync()
                .ContinueWith(task => task.Result.Body.Value.First(group => @group.Name == "Tuku TEST")))
            using (Task<Report> reportTask = client.Reports.GetReportsInGroupWithHttpMessagesAsync((await tableTalkGroup).Id).ContinueWith(task => task.Result.Body.Value.First(report => report.Name == "DirectQueryPC")))

            {
                var generateTokenRequestParameters = new GenerateTokenRequest(
                    accessLevel: "View",
                    datasetId: null,
                    identities: new List<EffectiveIdentity>
                    {
                        new EffectiveIdentity(
                            username: powerBi.Value.Username,
                            roles: new List<string> { "filterKel" },
                            datasets: new List<string> { (await reportTask).DatasetId })
                    });

                var tokenResponse = await client.Reports.GenerateTokenInGroupWithHttpMessagesAsync(
                    groupId: (await tableTalkGroup).Id,
                    reportKey: (await reportTask).Id,
                    requestParameters: generateTokenRequestParameters);
                // Generate Embed Configuration.
                var embedConfig = new EmbedConfig()
                {
                    EmbedToken = tokenResponse.Body,
                    EmbedUrl = (await reportTask).EmbedUrl,
                    Id = (await reportTask).Id
                };

                return View(embedConfig);
            }
        }

 

View solution in original post

1 REPLY 1
Mexicoder
Frequent Visitor

so i still dont know how to use custom header but i figured ouut how to add roles using the GenerateTokenRequest object and the GenerateTokenInGroupWithHttpMessagesAsync call.

 

 

    private async Task<string> GetTokenCredentials()
        {
            var credential = new UserPasswordCredential(powerBi.Value.Username, powerBi.Value.Password);

            // Authenticate using created credentials
            var authenticationContext = new AuthenticationContext(powerBi.Value.AuthorityUrl);
            var authenticationResult =
                await authenticationContext.AcquireTokenAsync(powerBi.Value.ResourceUrl, powerBi.Value.ClientId,
                    credential);

            if (authenticationResult == null)
            {
                Console.WriteLine("Authentication Failed");
                return string.Empty;
            }
            return authenticationResult.AccessToken;
        }



        public async Task<ActionResult> GetReportEmbedded()
        {
            // Create a user password credentials.
            var accessToken = await GetTokenCredentials();

            var tokenCredentials = new TokenCredentials(accessToken, "Bearer");

            // Generate Embed Token.

            using (var client = new PowerBIClient(new Uri(powerBi.Value.ApiUrl), tokenCredentials))
            using (Task<Group> tableTalkGroup = client.Groups.GetGroupsWithHttpMessagesAsync()
                .ContinueWith(task => task.Result.Body.Value.First(group => @group.Name == "Tuku TEST")))
            using (Task<Report> reportTask = client.Reports.GetReportsInGroupWithHttpMessagesAsync((await tableTalkGroup).Id).ContinueWith(task => task.Result.Body.Value.First(report => report.Name == "DirectQueryPC")))

            {
                var generateTokenRequestParameters = new GenerateTokenRequest(
                    accessLevel: "View",
                    datasetId: null,
                    identities: new List<EffectiveIdentity>
                    {
                        new EffectiveIdentity(
                            username: powerBi.Value.Username,
                            roles: new List<string> { "filterKel" },
                            datasets: new List<string> { (await reportTask).DatasetId })
                    });

                var tokenResponse = await client.Reports.GenerateTokenInGroupWithHttpMessagesAsync(
                    groupId: (await tableTalkGroup).Id,
                    reportKey: (await reportTask).Id,
                    requestParameters: generateTokenRequestParameters);
                // Generate Embed Configuration.
                var embedConfig = new EmbedConfig()
                {
                    EmbedToken = tokenResponse.Body,
                    EmbedUrl = (await reportTask).EmbedUrl,
                    Id = (await reportTask).Id
                };

                return View(embedConfig);
            }
        }

 

Helpful resources

Announcements
Las Vegas 2025

Join us at the Microsoft Fabric Community Conference

March 31 - April 2, 2025, in Las Vegas, Nevada. Use code MSCUST for a $150 discount! Prices go up Feb. 11th.

Feb2025 Sticker Challenge

Join our Community Sticker Challenge 2025

If you love stickers, then you will definitely want to check out our Community Sticker Challenge!

Jan NL Carousel

Fabric Community Update - January 2025

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