Embedsy 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”.

Defining a Blue Store RLS role in Power BI DesktopIn our sample report, a Store table is linked to Sales Data via the _StoreID column. The Store table has a StoreName column, and we want to build RLS roles on it. In Power BI Desktop, we've created a role called Blue Store that filters StoreName to 'Blue Store'.

2. Test Roles

Before publishing the report, it's important to simulate how data will appear to users based on their roles. Power BI Desktop includes a “View as” feature for exactly this. To test Row-Level Security (RLS) roles, open the “View as” menu and select the role you want to check. Once applied, the selected role appears in the top-left corner.

Testing an RLS role with the View as feature in Power BI DesktopThe 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 assigns users or Entra security groups to the relevant roles.

Assigning users and Entra security groups to RLS roles in the Power BI ServiceIn the Power BI Service, Entra security groups (recommended) or individual users can be added to each of the created roles.

RLS in Power BI Embedded

Implementing RLS in Power BI Embedded requires writing some code, but the goal stays exactly the same: each user only sees what they're supposed to. This is achieved with embed tokens, which define user-specific permissions when a report is embedded.

An embed token is a secure object that controls access to a report. When you embed a report, the token specifies:
  • which user is accessing the report, and
  • what data they're allowed to see, based on their assigned RLS role.
By baking RLS into token generation, you ensure data is filtered according to each user's role — a seamless and secure embedding experience.

Here's how to 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 described earlier. On the Embedsy Portal's User Configuration page, add a new report that uses RLS and assign one of the roles defined in the report, as shown below.

Assigning an RLS role to a report on the Embedsy Portal User Configuration page
The Embedsy Portal automatically detects reports that have RLS defined and won't let you save until a role is assigned. If you try, you'll see this warning.

Embedsy Portal warning that an RLS role must be assigned before saving

2. Test if it works as expected

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

Selecting a role in the Embedsy Portal View As Role feature
This lets you see the report exactly as a user with the selected role would. In this example, the report filters correctly to show only the Blue Store.

Embedsy Portal report filtered to the Blue Store via RLS

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.