PowerBi-嵌入式 - 未经授权

发布于 2025-01-28 07:00:31 字数 4594 浏览 5 评论 0 原文

我一直在尝试不运气,以获取嵌入令牌,以便能够将我的PowerBi报告嵌入我现有的.NETCORE WEB API应用程序中。前端看起来像是Power BI为我准备的超级简单1个简单的反应组件。

但是对于后端来说,我实际上是在圈子。

我到了我决定这样做的最干净的方法是通过HTTP触发功能。
(请参阅此信息: https> https:https:// www。 taygan.co/blog/2018/05/14/embedded-analytics-with-power-bi

是一个重要的旁注:我确实已经授予了我的申请API)

另一个旁注是,我试图做主用户,应用程序拥有数据方法

另一个旁注是,您会看到上面的链接,代码显示您使用Microsoft不再支持(似乎是)的方法获得AAD auth

using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.PowerBI.Api;
using Microsoft.PowerBI.Api.Models;
using Microsoft.Rest;
using Newtonsoft.Json;

namespace PowerBiExample
{
    public class EmbedContent
    {
        public string EmbedToken { get; set; }
        public string EmbedUrl { get; set; }
        public string ReportId { get; set; }
    }
    
    public static class Test
    {
        private static string tenantId = "this is the id of my entire organization";
         static string authorityUrl = $"https://login.microsoftonline.com/{tenantId}";
         static string resourceUrl = "https://analysis.windows.net/powerbi/api";
        static string apiUrl = "https://api.powerbi.com/";
        private static string clientId = "this is the client id of my application that i gave delegate permissions to"; 
        private static string clientSecret = "this is the secret of the application i gave delegate permissions to";
        private static string username = "ad master user that i WANTED to sign into power bi with";
        private static string password = "that ad users pw"; 
        private static Guid groupId = Guid.Parse("workspaceid in powerbi"); 
        private static Guid reportId = Guid.Parse("report id from within that workspace"); 
        
        
        [FunctionName("Test")]
        public static async Task<IActionResult> RunAsync(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log)
        {

            var credential = new ClientCredential(clientId, clientSecret);
            var authenticationContext = new AuthenticationContext(authorityUrl);
            // var authenticationResult = await authenticationContext.AcquireTokenAsync(resourceUrl, clientId, credential);
            var authenticationResult = await authenticationContext.AcquireTokenAsync(resourceUrl, credential);
            string accessToken = authenticationResult.AccessToken;
            var tokenCredentials = new TokenCredentials(accessToken, "Bearer");
    
            using (var client = new PowerBIClient(new Uri(apiUrl), tokenCredentials))
            {
                // Embed URL
                Report report = client.Reports.GetReportInGroup(groupId, reportId);
                string embedUrl = report.EmbedUrl;

                // Embed Token
                var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                EmbedToken embedToken = client.Reports.GenerateTokenInGroup(groupId, reportId, generateTokenRequestParameters);

                // JSON Response
                EmbedContent data = new EmbedContent();
                data.EmbedToken = embedToken.Token;
                data.EmbedUrl = embedUrl;
                data.ReportId = reportId.ToString();
                var s = JsonConvert.SerializeObject(data);
                return new JsonResult(s);
                // JavaScriptSerializer js = new JavaScriptSerializer();
                // string jsonp = "callback(" +  js.Serialize(data) + ");";
                //
                // // Return Response
                // return new HttpResponseMessage(HttpStatusCode.OK) 
                // {
                //     Content = new StringContent(jsonp, Encoding.UTF8, "application/json")
                // };
            }
        }
    }
}

令牌。我没有返回嵌入令牌。我对此感到未经授权。

也很重要的说明:1。我也没有像在这里启用服务校长那样在这里学习。microsoft.com/en-us/power-bi/enterprise/ (我的该部门说我不能)。和2。它们不是工作空间上的管理员或成员,但是当我尝试将其添加为成员时,它们就不可用。这是一个应用程序,而不是用户或组。我该怎么办

I have been trying WITH NO LUCK, to get an embed token to be able to embed my powerbi reports into my existing .netcore web api application. The front end looks like a super easy 1 simple react component that power bi has prepared for me.

But for the backend, I'm literally going in circles.

I got to the point where I decided the cleanest way for me to do this would be through an HTTP Trigger function.
(see this: https://www.taygan.co/blog/2018/05/14/embedded-analytics-with-power-bi )

As an important side note: I DID already grant my application the necessary delegate READ permissions to the power bi Apis)

Another side note, is that I am attempting to do the master user, app owns data approach

Another side note, is that you will see that my link above, the code shows you to get an AAD auth token using a method that is no longer supported (seemingly) by microsoft, so I changed that line of code as you'll see below

using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.PowerBI.Api;
using Microsoft.PowerBI.Api.Models;
using Microsoft.Rest;
using Newtonsoft.Json;

namespace PowerBiExample
{
    public class EmbedContent
    {
        public string EmbedToken { get; set; }
        public string EmbedUrl { get; set; }
        public string ReportId { get; set; }
    }
    
    public static class Test
    {
        private static string tenantId = "this is the id of my entire organization";
         static string authorityUrl = 
quot;https://login.microsoftonline.com/{tenantId}";
         static string resourceUrl = "https://analysis.windows.net/powerbi/api";
        static string apiUrl = "https://api.powerbi.com/";
        private static string clientId = "this is the client id of my application that i gave delegate permissions to"; 
        private static string clientSecret = "this is the secret of the application i gave delegate permissions to";
        private static string username = "ad master user that i WANTED to sign into power bi with";
        private static string password = "that ad users pw"; 
        private static Guid groupId = Guid.Parse("workspaceid in powerbi"); 
        private static Guid reportId = Guid.Parse("report id from within that workspace"); 
        
        
        [FunctionName("Test")]
        public static async Task<IActionResult> RunAsync(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log)
        {

            var credential = new ClientCredential(clientId, clientSecret);
            var authenticationContext = new AuthenticationContext(authorityUrl);
            // var authenticationResult = await authenticationContext.AcquireTokenAsync(resourceUrl, clientId, credential);
            var authenticationResult = await authenticationContext.AcquireTokenAsync(resourceUrl, credential);
            string accessToken = authenticationResult.AccessToken;
            var tokenCredentials = new TokenCredentials(accessToken, "Bearer");
    
            using (var client = new PowerBIClient(new Uri(apiUrl), tokenCredentials))
            {
                // Embed URL
                Report report = client.Reports.GetReportInGroup(groupId, reportId);
                string embedUrl = report.EmbedUrl;

                // Embed Token
                var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                EmbedToken embedToken = client.Reports.GenerateTokenInGroup(groupId, reportId, generateTokenRequestParameters);

                // JSON Response
                EmbedContent data = new EmbedContent();
                data.EmbedToken = embedToken.Token;
                data.EmbedUrl = embedUrl;
                data.ReportId = reportId.ToString();
                var s = JsonConvert.SerializeObject(data);
                return new JsonResult(s);
                // JavaScriptSerializer js = new JavaScriptSerializer();
                // string jsonp = "callback(" +  js.Serialize(data) + ");";
                //
                // // Return Response
                // return new HttpResponseMessage(HttpStatusCode.OK) 
                // {
                //     Content = new StringContent(jsonp, Encoding.UTF8, "application/json")
                // };
            }
        }
    }
}

I DO get the Authorization Token returned. I DO NOT get the Embed Token returned. I get unauthorized for that.

Also important note: 1. I also didn't enable Service Principal like it says to do here learn.microsoft.com/en-us/power-bi/enterprise/… (my IT dept said I can't). and 2. they are not an admin or member on the workspace but when I try to add them as member, they are not available. It's an Application, not a user or a group. What should I do

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北城半夏 2025-02-04 07:00:31

请检查以下几点是否可以让您有一个工作。

  1. 可能需要提琴手痕迹进行进一步调查。所需的
    注册申请可能缺少许可范围
    在Azure AD中。 验证所需的范围存在于
    Azure Portal ex中的Azure AD的应用程序注册:OpenID,
    配置文件,离线等,具体取决于要求和用户
    登录。

使用主用户时,您需要定义应用程序的 委派
权限
(称为范围)。主用户或Power BI
要求管理使用这些权限的同意
Power Bi Rest Apis。

  1. 对于主用户, 赠款权限
    Azure门户。
  2. 还检查提供的 组ID是否正确
  3. 也用于分析服务, Master用户必须是一个
    门户管理员

注意:出于安全原因,嵌入令牌的寿命设置为用于调用该代币的Azure AD代币的剩余寿命
Generateken Api。

因此,如果您使用相同的Azure AD令牌来生成几个嵌入令牌,则每个调用 将较短。
有时,这可能是由于嵌入代币到期而导致未经授权错误的原因,

And also check if you need to provide datasetId

Some references:

  1. 注册一个应用程序以嵌入power bi bi嵌入的power bi content
    分析应用程序 - Power BI | Microsoft Docs
  2. 了解嵌入功率BI所需的权限令牌
    应用-Power BI |微软文档

Please check if below points can give an idea to work around.

  1. A fiddler trace may be required to investigate further. The required
    permission scope may be missing for the registered application
    within Azure AD. Verify the required scope is present within the
    app registration for Azure AD within the Azure portal ex: openid ,
    profile, offline etc depending on the requirement and the user
    logged in.

When using a master user, you'll need to define your app's delegated
permissions
( known as scopes). The master user or Power BI
admin is required to grant consent for using these permissions using
the Power BI REST APIs.

  1. For master users, it is essential to grant permissions from the
    Azure portal.
  2. Also check if the group Id provided is correct,
  3. Also For Analysis Services, the master user has to be a
    gateway admin.

enter image description here

  • Your web app uses a user account to authenticate against Azure AD
    and get the Azure AD token. The master user needs to have a Power
    BI Pro
    or a Premium Per User (PPU) license.
  • After successful authentication against Azure AD, your web app will
    generate an embed token to allow its users to access specific
    Power BI content.
  • Please go through this considerations to generate embed token
    carefully and give proper permissions.

Note: For security reasons, the lifetime of the embed token is set to the remaining lifetime of the Azure AD token used to call the
GenerateToken API.

Therefore, if you use the same Azure AD token to generate several embed tokens, the lifetime of the generated embed tokens will be shorter with each call.
Sometimes that can be the reason for the unauthorized error due to expiry of embed token

And also check if you need to provide datasetId

Some references:

  1. Unauthorized response on GetReportInGroupAsync PowerBI Embedded
    API call using Service Principal - Stack Overflow
  2. Register an app to embed Power BI content in a Power BI embedded
    analytics application - Power BI | Microsoft Docs
  3. Understand the permission tokens needed for embedding a Power BI
    application - Power BI | Microsoft Docs
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文