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
santiagomur
Resolver II
Resolver II

RLS LIVE CONNECTION DATASET

Hi, 

 

i have a problem with the config  of the rls, i already use rls and it works fine, but now the plan is to make 1 dataset and many reports, i try to use the same config that i use when is 1 report per dataset and doesnt works, i ont know if i need to make some changes on the config.

 

the config is this 

  #r "System.Web.Extensions"  
    using System.Configuration;  
    using System.Net;  
    using System.Text;  
    using System.Web.Script.Serialization;  
    using Microsoft.IdentityModel.Clients.ActiveDirectory;  
    using Microsoft.PowerBI.Api.V2;  
    using Microsoft.PowerBI.Api.V2.Models;  
    using Microsoft.Rest;  
      
    // Static Values      
    static string authorityUrl = ConfigurationManager.AppSettings["AUTHORITY_URL"];    
    static string resourceUrl = ConfigurationManager.AppSettings["RESOURCE_URL"];      
    static string apiUrl = ConfigurationManager.AppSettings["POWERBI_API_URL"];  
    static string clientId = ConfigurationManager.AppSettings["PBIE_CLIENT_ID"];
    static string username = ConfigurationManager.AppSettings["PBIE_USERNAME"];
    static string password = ConfigurationManager.AppSettings["PBIE_PASSWORD"];      
    static string defaultUser = "";
    static string defaultRol = "USUARIO";
    static string defaultReport = "";
    static string defaultGroup = "";
    static string defaultDashboard = "";
    static string defaultDataset = "";
      
    public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)  
    {  
		log.Info( string.Format("Dump request:\n {0}",req.ToString()));
        
        PostData userData = new PostData();

        //Recover req PostData
        PostData jsonData = await req.Content.ReadAsAsync<PostData>();
        if (jsonData != null){
           log.Info ("JsonReq: "+ jsonData.ToString());
           userData = prepareUserData(jsonData);
        } else {
            //Default values
            userData = prepareUserData(new PostData());
        }
        log.Info("userData: " + userData.ToString());


        // Authenticate with Azure Ad > Get Access Token > Get Token Credentials  
        var credential = new UserPasswordCredential(username, password);  

        var authenticationContext = new AuthenticationContext(authorityUrl);  
        var authenticationResult = await authenticationContext.AcquireTokenAsync(resourceUrl, clientId, credential);  
        string accessToken = authenticationResult.AccessToken;  
        var tokenCredentials = new TokenCredentials(accessToken, "Bearer"); 
        log.Info ("Llega");
        // PowerBI method  
        using (var client = new PowerBIClient(new Uri(apiUrl), tokenCredentials))  
        {  
            // Embed URL
            GenerateTokenRequest generateTokenRequestParameters;
            generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");  
            string embedUrl;


            /////////////////////////////// DASHBOARD ///////////////////////////////
            if (!string.IsNullOrWhiteSpace(userData.dashboardId)) 
            {
                embedUrl = "https://app.powerbi.com/dashboardEmbed";
                log.Info ("Llega1");
                var tokenResponse = await client.Dashboards.GenerateTokenInGroupAsync(userData.groupId, userData.dashboardId, generateTokenRequestParameters);
                
                // JSON Response  
                EmbedContent data = new EmbedContent();  
                data.EmbedToken = tokenResponse.Token;  
                data.EmbedUrl = embedUrl;  
                data.ReportId = userData.dashboardId;
                data.DashboardId = userData.dashboardId;

                JavaScriptSerializer js = new JavaScriptSerializer();  
                string jsonp = "callback(" +  js.Serialize(data) + ");";
                log.Info(jsonp);

                // Return Response  
                return new HttpResponseMessage(HttpStatusCode.OK)   
                {  
                    Content = new StringContent(jsonp, Encoding.UTF8, "application/json")  
                }; 
            }

            else
            /////////////////////////////// REPORT ///////////////////////////////
            {
                embedUrl = "https://app.powerbi.com/reportEmbed";
                log.Info ("Llega2");
                Report report = client.Reports.GetReportInGroup(userData.groupId, userData.reportId);  
                var result = new EmbedConfig();
                log.Info(embedUrl);
                
                string allParameter = String.Concat(userData.userID,";",userData.companyY2MX,";",userData.environment,";",userData.mediatorCode,";",userData.commercialCode); 
                log.Info("allParameter: " + allParameter);
                
                result = new EmbedConfig { Username = allParameter, Roles = userData.roles};
            
                var datasets = await client.Datasets.GetDatasetByIdInGroupAsync(userData.groupId, report.DatasetId);
                log.Info("DataSet: " + report.DatasetId);
                result.IsEffectiveIdentityRequired = datasets.IsEffectiveIdentityRequired;
                result.IsEffectiveIdentityRolesRequired = datasets.IsEffectiveIdentityRolesRequired;
                log.Info("Dataset IsEffectiveIdentityRequired: " + result.IsEffectiveIdentityRequired);
                log.Info("Dataset IsEffectiveIdentityRolesRequired: " + result.IsEffectiveIdentityRolesRequired);

                //GenerateTokenRequest generateTokenRequestParameters;
                log.Info ("Llega3");
                if (!string.IsNullOrWhiteSpace(userData.userID))
                {
                    if (result.IsEffectiveIdentityRolesRequired==true)
                    {   
                        var rls = new EffectiveIdentity(allParameter, new List<string> {  report.DatasetId });
                        if (!string.IsNullOrWhiteSpace(userData.roles))
                        {
                            var rolesList = new List<string>();
                            rolesList.AddRange(userData.roles.Split(','));
                                            
                            rls.Roles = rolesList;                        
                        }
                        // Generate Embed Token with effective identities.
                        generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view", identities: new List<EffectiveIdentity> { rls });
                        log.Info("Token Request with EffectiveIdentity");
                        }
                    else
                    {
                        // Generate Embed Token for reports without effective identities.
                        generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                        log.Info("Token Request without EffectiveIdentity");
                    }
                }
                else
                {
                    // Generate Embed Token for reports without effective identities.
                    generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                    log.Info("Token Request without EffectiveIdentity");
                }
                log.Info("Token Request " + userData);
                log.Info("generateTokenRequestParameters " + generateTokenRequestParameters);



                var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(userData.groupId, userData.reportId, generateTokenRequestParameters);


                // JSON Response  
                EmbedContent data = new EmbedContent();  
                data.EmbedToken = tokenResponse.Token;  
                data.EmbedUrl = embedUrl;
                data.ReportId = userData.reportId;
                data.DashboardId = userData.reportId;
                
                JavaScriptSerializer js = new JavaScriptSerializer();  
                string jsonp = "callback(" +  js.Serialize(data) + ");";  
                log.Info(jsonp);

                // Return Response  
                return new HttpResponseMessage(HttpStatusCode.OK)   
                {  
                    Content = new StringContent(jsonp, Encoding.UTF8, "application/json")  
                }; 
            }
        }  
    } 

    public static PostData prepareUserData(PostData data) {
        PostData userData = new PostData();  

         if (!string.IsNullOrWhiteSpace(data.userID)){
            userData.userID = data.userID;
         } else {
             userData.userID = defaultUser;
         }
         if (!string.IsNullOrWhiteSpace(data.roles)){
            userData.roles = data.roles;
         } else {
             userData.roles = defaultRol;
         }
         if (!string.IsNullOrWhiteSpace(data.reportId)){
            userData.reportId = data.reportId;
         } else {
             userData.reportId = defaultReport;
         }
         if (!string.IsNullOrWhiteSpace(data.groupId)){
            userData.groupId = data.groupId;
         } else {
             userData.groupId = defaultGroup;
         }
         if (!string.IsNullOrWhiteSpace(data.dashboardId)){
            userData.dashboardId = data.dashboardId;
         } else {
             userData.dashboardId = defaultDashboard;
         }

         if (!string.IsNullOrWhiteSpace(data.environment)){
            userData.environment = data.environment;
         } else {
             userData.environment = "4";
         }
         if (!string.IsNullOrWhiteSpace(data.companyY2MX)){
            userData.companyY2MX = data.companyY2MX;
         } else {
             userData.companyY2MX = "G";
         }
         if (!string.IsNullOrWhiteSpace(data.mediatorCode)){
            userData.mediatorCode = data.mediatorCode;
         } else {
             userData.mediatorCode = "0";
         }
         if (!string.IsNullOrWhiteSpace(data.commercialCode)){
            userData.commercialCode = data.commercialCode;
         } else {
             userData.commercialCode = "0";
         }
          if (!string.IsNullOrWhiteSpace(data.datasetId)){
            userData.datasetId = data.datasetId;
         } else {
             userData.datasetId = defaultDataset;
         }
           
         return userData;
    }

    //Json Response Class  
    public class EmbedContent  
    {  
        public string EmbedToken { get; set; }  
        public string EmbedUrl { get; set; }  
        public string ReportId { get; set; }  
        public string DashboardId { get; set; }
    }

    //Json Request Post Class.
    public class PostData
    {
        public string userID { get;set; }
        public string environment { get;set; }
        public string roles { get;set; }
        public string reportId { get;set; }
        public string groupId { get;set; }        
        public string companyY2MX { get;set; }
        public string mediatorCode { get;set; }
        public string commercialCode { get;set; }
        public string dashboardId { get;set; }
        public string datasetId { get;set; }

        public override string ToString()
        {
            return "userID : " + userID + 
            ", environment: " + environment +
            ", roles: " + roles +
            ", reportId: " + reportId +
            ", groupId: " + groupId +
            ", dashboardId: " + dashboardId +
            ", cia: " + companyY2MX +
            ", mediatorCode: " + mediatorCode +
            ", commercialCode: " + commercialCode +
            ", datasetId: " + datasetId;
        }
    }  


    public class EmbedConfig
    {
        public string Id { get; set; }
        public string EmbedUrl { get; set; }
        public EmbedToken EmbedToken { get; set; }
        public int MinutesToExpiration
        {
            get
            {
                var minutesToExpiration = EmbedToken.Expiration.Value - DateTime.UtcNow;
                return minutesToExpiration.Minutes;
            }
        }
        public bool? IsEffectiveIdentityRolesRequired { get; set; }
        public bool? IsEffectiveIdentityRequired { get; set; }
        public bool EnableRLS { get; set; }
        public string Username { get; set; }
        public string Roles { get; set; }
        public string ErrorMessage { get; internal set; }
    }
    
1 REPLY 1
V-lianl-msft
Community Support
Community Support

Hi @santiagomur ,

 

Based on your description, could you use this dataset as a shared dataset and Other reports are then created based on this shared dataset.

 

 

Best Regards,
Liang
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.

 

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.