site logo

Sep 18, 2024

Row-Level-Security (RLS) in Power BI Embedded

ByVlad Mihanta

Row-Level-Security (RLS) in Power BI Embedded

Implementing Row-Level Security (RLS) in Power BI Embedded

What is Row-Level Security (RLS)?

Row-Level Security (RLS) is a critical data security feature that restricts access to data at the row level based on user roles. It guarantees that users only see information they have access to. This allows the use of the same Semantic Model for multiple use cases and eliminates the need to duplicate models just to split access rights.

Configuring roles in Power BI Desktop allows users to automatically apply RLS configurations when they access reports. Based on these role-based filters, the system dynamically modifies the data the user can view.

Types of RLS: Dynamic vs. Static

Static RLS

Static RLS involves establishing fixed filters for user roles, meaning these filters stay the same regardless of the user. This is a simple method usually applied in cases when user roles and the data they require access to are well specified. Static filters, for instance, guarantee that a sales team, logging in with any user, views only the data they require, such as sales statistics specific to a given region.

Dynamic RLS

More flexibility is available with Dynamic RLS. In this case, DAX functions like USERPRINCIPALNAME() and USERNAME() are used to apply the filters based on the identification of the logged-in user. As a result, every user can see the data in a unique way. This setup allows to only have a few roles defined and use the same role for all or most users.

Setting Up RLS in Power BI

The journey of implementing RLS begins in Power BI Desktop. The setup process involves these key steps:

1. Define Roles

Use Power BI Desktop to create roles. Each role includes specific filters applied to tables in the semantic model. For example, a role named “Blue Store“ might include a filter such as [StoreName] = “Blue Store“.

DefineIn our sample report, we have a Store Table which is linked to Sales Data via the _StoreID column. In our Store table, we have a column StoreName on which we want to create RLS roles. In Power BI Desktop, we have created a role called Blue Store which filters the StoreName by 'Blue Store'

2. Test Roles

Before publishing the report, it is important to simulate how data will be displayed to users based on their roles. Power BI Desktop includes a “View as Role“ feature for testing purposes. To test Row-Level Security (RLS) roles directly in Power BI Desktop, navigate to the “View as“ menu and select the role you want to test. Once applied, you'll see the selected role show up in the top left corner.

DefineThe displayed Profit is now much lower than before because the tested role only has access to one Store.

3. Publish and Assign Roles

Once satisfied with the roles, the report is published to the Power BI Service. A user with the appropriate access then assignes users or Entra Security groups to the appropriate roles.

DefineIn the Power BI Service, Entra Security Groups (recommended) or users can be added to each of the created roles.

RLS in Power BI Embedded

Of course, the implementation of RLS in Power BI Embedded requires writing code. The goal remains the same: each user can only see what they're supposed to see. This is achieved through the use of embed tokens, which define user-specific permissions when embedding Power BI reports.

An embed token is a secure object that controls access to reports. When embedding a report, the token specifies:
  • Which user is accessing the report.
  • What data they are allowed to see based on their assigned RLS role.

  • By including RLS in the token generation process, you ensure data is filtered according to the user’s role, providing a seamless and secure embedding experience.

    Here’s how you can generate an embed token with the 'Blue Store' role:
    1// Import necessary modules
    2const msal = require('@azure/msal-node');
    3const axios = require('axios');
    4
    5// Function to generate an embed token with RLS applied
    6async function getEmbedToken(reportId, datasetIds, targetWorkspaceId = null) {
    7  // Authentication configuration for Azure AD
    8  const config = {
    9    auth: {
    10      clientId: '<YOUR_CLIENT_ID>', // Azure AD Application Client ID
    11      authority: 'https://login.microsoftonline.com/<YOUR_TENANT_ID>', // Azure AD Tenant ID
    12      clientSecret: '<YOUR_CLIENT_SECRET>', // Azure AD Application Client Secret
    13    },
    14  };
    15
    16  // Create a Confidential Client Application object
    17  const cca = new msal.ConfidentialClientApplication(config);
    18
    19  // Define the scope for the Power BI REST API
    20  const tokenRequest = {
    21    scopes: ['https://analysis.windows.net/powerbi/api/.default'],
    22  };
    23
    24  try {
    25    // Acquire an access token to authenticate the API call
    26    const authResult = await cca.acquireTokenByClientCredential(tokenRequest);
    27    const accessToken = authResult.accessToken;
    28
    29    // Define the Effective Identity for RLS
    30    const effectiveIdentity = {
    31      username: 'static_user@example.com', // Static username for RLS
    32      roles: ['Blue Store'], // RLS role to apply
    33      datasets: datasetIds, // List of dataset IDs
    34    };
    35
    36    // Create the request body for generating the embed token
    37    const generateTokenRequestBody = {
    38      datasets: datasetIds.map((id) => ({ id: id })), // Dataset IDs
    39      reports: [{ id: reportId }], // Report ID
    40      targetWorkspaces: targetWorkspaceId
    41        ? [{ id: targetWorkspaceId }] // Target workspace if provided
    42        : null,
    43      identities: [effectiveIdentity], // RLS identities
    44    };
    45
    46    // Make the API call to generate the embed token
    47    const embedTokenResponse = await axios.post(
    48      'https://api.powerbi.com/v1.0/myorg/GenerateToken',
    49      generateTokenRequestBody,
    50      {
    51        headers: {
    52          'Content-Type': 'application/json',
    53          Authorization: `Bearer accessToken`, // Bearer token authentication
    54        },
    55      }
    56    );
    57
    58    // Return the generated embed token
    59    return embedTokenResponse.data.token;
    60  } catch (error) {
    61    console.error('Error generating embed token:', error.response ? error.response.data : error.message);
    62    throw error;
    63  }
    64}
    65
    66// Example usage of the getEmbedToken function
    67(async () => {
    68  // Replace these placeholder values with your actual IDs
    69  const reportId = '<YOUR_REPORT_ID>'; // GUID of the report to embed
    70  const datasetIds = ['<YOUR_DATASET_ID>']; // Array of dataset GUIDs
    71  const targetWorkspaceId = '<YOUR_WORKSPACE_ID>'; // GUID of the target workspace (optional)
    72
    73  try {
    74    // Call the function to get the embed token
    75    const embedToken = await getEmbedToken(reportId, datasetIds, targetWorkspaceId);
    76    console.log('Embed Token:', embedToken);
    77  } catch (error) {
    78    console.error('Failed to retrieve embed token:', error);
    79  }
    80})();
    Visit the Microsoft documentation for more information

    RLS in the Embedsy Portal: Out-of-the-box RLS in Power BI Embedded

    After configuring RLS in Power BI, the Embedsy Portal allows users to assign these roles with minimal effort.

    The best part? We’ve already done all the heavy lifting for you. The Embedsy Portal comes with full RLS integration out of the box. This means you don’t need to write any code or worry about the technical details. Everything is handled seamlessly within the platform.

    Here’s how RLS is applied in the Embedsy Portal:

    1. Assign existing RLS Role

    Remember that the RLS roles themselves are created in Power BI Desktop as previously described. In Embedsy Portal's User Configuration page, add a new report that contains RLS. Add one of the roles defined in the report, as illustrated in this image.

    Define
    Note that the Embedsy Portal automatically detects reports with RLS defined and doesn't allow saving if no RLS role was added in the Embedsy Portal. This is the warning message shown if this happens.

    Define

    2. Test if it works as expected

    Use Embedsy Portal's View As Role feature to see if the RLS is applied correctly.

    Define
    With this functionality, you can see the report exactly as a user having the selected role applied. In this example, the report filters correctly to display only the Blue Store.

    Define

    And that's it, you have successfully applied RLS in Power BI Embedded and are ready to give access to the relevant users.

    The Embedsy Advantage: Why Choose the Embedsy Portal for RLS

    While many platforms offer RLS functionality, the Embedsy Portal stands out with its unique approach:

    Inclusive Access

    Unlike other platforms that only allow RLS in premium plans, the Embedsy Portal offers RLS functionality to all users at no additional cost. This democratizes access to advanced data-security features, making it accessible for businesses of all sizes.

    Ease of Use

    Setting up RLS in the Embedsy Portal is straightforward, thanks to its role mapping system. Once RLS is configured in Power BI, activating it in the Embedsy Portal requires minimal effort, saving administrators time and reducing complexity.

    Cost-Effectiveness

    By not imposing additional charges for RLS, the Embedsy Portal provides a cost-effective solution for embedding secure analytics. Organizations can achieve robust data security without exceeding their budgets.

    Key Takeaway

    The Embedsy Portal brings Row-Level Security to the forefront of embedded analytics, making it an accessible, user-friendly, and cost-effective solution. By maintaining consistency with Power BI’s setup process and eliminating unnecessary steps, the Embedsy Portal ensures a smooth transition from traditional analytics to embedded environments.

    With no additional costs and easy configuration, the Embedsy Portal empowers organizations to extend secure, role-based data access to their embedded analytics without compromise.