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

The ultimate Microsoft Fabric, Power BI, Azure AI & SQL learning event! Join us in Las Vegas from March 26-28, 2024. Use code MSCUST for a $100 discount. Register Now

Reply
santiagomur
Resolver II
Resolver II

RLS LIVE CONNECTION

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

#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);
2 REPLIES 2
nickyvv
Community Champion
Community Champion

Hi @santiagomur.

 

I see a lot of code, but I'm not sure where to look at? What exactly is the issue? Is there an error, or is RLS not working?

Please be as specific as you can when describing the problem, that helps us to understand it better.



Did I answer your question? Mark my post as a solution!

Blog: nickyvv.com | @NickyvV


Hi, 
when i use this config on a normal 1 to 1 report dataset is fine, but now i try many report to one dataset and the rls dont works. 

 

 

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");
                        }

 

 





 

Helpful resources

Announcements
Fabric Community Conference

Microsoft Fabric Community Conference

Join us at our first-ever Microsoft Fabric Community Conference, March 26-28, 2024 in Las Vegas with 100+ sessions by community experts and Microsoft engineering.

February 2024 Update Carousel

Power BI Monthly Update - February 2024

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

Fabric Career Hub

Microsoft Fabric Career Hub

Explore career paths and learn resources in Fabric.

Fabric Partner Community

Microsoft Fabric Partner Community

Engage with the Fabric engineering team, hear of product updates, business opportunities, and resources in the Fabric Partner Community.

Top Solution Authors
Top Kudoed Authors