Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions CS/BlazorAuth/Code/CustomDashboardStorage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public class CustomDashboardStorage : IEditableDashboardStorage {
public CustomDashboardStorage(IWebHostEnvironment hostingEnvironment, IDashboardUserProvider dashboardUserProvider) {
this.dashboardUserProvider = dashboardUserProvider;
this.DashboardStorageFolder = hostingEnvironment.ContentRootFileProvider.GetFileInfo("App_Data/Dashboards").PhysicalPath!
?? throw new InvalidOperationException("Dashboard storage dashboardPath is not available.");
?? throw new InvalidOperationException("The dashboard storage folder is not available.");
}

public IEnumerable<DashboardInfo> GetAvailableDashboardsInfo() {
Expand Down Expand Up @@ -67,9 +67,11 @@ public void SaveDashboard(string dashboardID, XDocument dashboard) {
File.WriteAllText(dashboardPath, dashboard.ToString());
}

// Dashboard IDs and names come from the client.
// Verifies that the resulting path is inside the dashboard storage folder.
void ValidateDashboardPath(string dashboardPath) {
if(!SafePath.IsRooted(DashboardStorageFolder, dashboardPath))
throw new InvalidOperationException("Invalid dashboard folder dashboardPath");
throw new InvalidOperationException("The dashboard path is outside the dashboard storage folder.");
}
}
}
4 changes: 4 additions & 0 deletions CS/BlazorAuth/Code/DashboardUserProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,16 @@ public interface IDashboardUserProvider {
string? GetUserName();
}

// Obtains the current user name from the AuthenticationStateProvider.
public class DashboardUserProvider : IDashboardUserProvider {
readonly AuthenticationStateProvider authProvider;

public DashboardUserProvider(AuthenticationStateProvider provider) {
this.authProvider = provider;
}

// Dashboard storage and provider methods are synchronous.
// This method reads the authentication state only if it is already available and does not block the circuit.
public string? GetUserName() {
var stateTask = authProvider.GetAuthenticationStateAsync();
if(!stateTask.IsCompletedSuccessfully)
Expand All @@ -27,6 +30,7 @@ public DashboardUserProvider(AuthenticationStateProvider provider) {
return ReadName(state);
}

// Identity user names are email addresses: "admin@gmail.com" -> "admin".
static string? ReadName(AuthenticationState state) {
var identity = state.User.Identity;
return identity?.IsAuthenticated == true ? identity.Name?.Split('@')[0] : null;
Expand Down
2 changes: 2 additions & 0 deletions CS/BlazorAuth/Code/MultiTenantDashboardConfigurator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ public MultiTenantDashboardConfigurator(
SetDashboardStorage(dashboardStorage);
SetDBSchemaProvider(dbSchemaProvider);

// Restricts unauthorized users and guests: they cannot create, edit, or save dashboards on the server.
// The handler reads the user name on each call, as do the custom storages and providers: the authentication state can change while the circuit is active.
VerifyClientTrustLevel += (s, e) => {
var userName = dashboardUserProvider.GetUserName();

Expand Down
2 changes: 1 addition & 1 deletion CS/BlazorAuth/Pages/Index.razor
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

<h1>Multi-tenant Dashboard for Blazor</h1>

<p><a href="Identity/Account/Login">Log in</a> as one of the user below and navigate to the <a href="dashboard">Web Dashboard</a> page to see the result:</p>
<p><a href="Identity/Account/Login">Log in</a> as one of the users below and navigate to the <a href="dashboard">Web Dashboard</a> page to see the result:</p>

<code>
<p>Email: admin@gmail.com<br />Password: 1*234aB</p>
Expand Down
2 changes: 2 additions & 0 deletions CS/BlazorAuth/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
builder.Services.AddDevExpressControls();
builder.Services.AddRazorPages();

// Register dashboard storages and providers as scoped services.
// In the Blazor circuit, each user connection gets its own instances.
builder.Services.AddScoped<IDataSourceWizardConnectionStringsProvider, CustomConnectionStringProvider>();
builder.Services.AddScoped<IDataSourceStorage, CustomDataSourceStorage>();
builder.Services.AddScoped<IEditableDashboardStorage, CustomDashboardStorage>();
Expand Down
42 changes: 22 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,25 @@
[![](https://img.shields.io/badge/📖_How_to_use_DevExpress_Examples-e9f6fc?style=flat-square)](https://docs.devexpress.com/GeneralInformation/403183)
[![](https://img.shields.io/badge/💬_Leave_Feedback-feecdd?style=flat-square)](#does-this-example-address-your-development-requirementsobjectives)
<!-- default badges end -->
# Dashboard for Blazor - How to Implement Multi-Tenant Dashboard Architecture using the ASP.NET Core's Identity Authentication System
# Blazor BI Dashboard - Implement Multi-Tenant Dashboard Architecture using the ASP.NET Core's Identity Authentication System

This example shows how to configure the Dashboard component for Blazor so that it works in the multi-user environment.
This example configures the Dashboard component to work in a multi-user environment.

The example uses ASP.NET Core Identity for authentication and Blazor's `AuthenticationStateProvider` to identify the current user. It configures dashboard storage, data sources, connection strings, and schema access based on that user's identity.
The Dashboard component [processes requests in the Blazor circuit](https://docs.devexpress.com/Dashboard/406269/web-dashboard/integrate-dashboard-component/dashboard-component-for-blazor/process-requests-in-blazor-circuit) (the SignalR connection between the browser and the server). The example uses ASP.NET Core Identity for authentication and Blazor [`AuthenticationStateProvider`](https://learn.microsoft.com/en-us/aspnet/core/blazor/security/authentication-state) to determine the current user. Custom storages and providers rely on the user name to return user-specific dashboards, data sources, connection strings, and database schema.

![](web-dashboard-blazor-auth.png)
![Blazor BI Dashboard](web-dashboard-blazor-auth.png)

## How to Launch
## Launch the Application

This example was created based on the **Blazor Server App** Visual Studio template with the *Authentication Type = 'Individual Accounts'* setting (see [Secure ASP.NET Core Blazor Server apps](https://docs.microsoft.com/en-us/aspnet/core/blazor/security/server/?view=aspnetcore-5.0&tabs=visual-studio)). The example uses the [ASP.NET Core's Identity mechanism](https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-5.0&tabs=visual-studio) for authentication. For this reason, you need to follow the steps below to initialize the Identity database and register required user accounts in it:
This example is based on the **Blazor Server App** Visual Studio template with the *Authentication Type = 'Individual Accounts'* option (refer to [Secure ASP.NET Core server-side Blazor apps](https://learn.microsoft.com/en-us/aspnet/core/blazor/security/server/)). The example uses the [ASP.NET Core Identity mechanism](https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity) for authentication. Follow the steps below to initialize the Identity database and register required user accounts:

1) Apply the `00000000000000_CreateIdentitySchema` migration to the `aspnet-BlazorAuth-...` database. You can run the following command in the Package Manager Console for this purpose:
1) Run the following Package Manager Console command to apply the `00000000000000_CreateIdentitySchema` migration to the SQL Server LocalDB database (specified in the [appsettings.json](./CS/BlazorAuth/appsettings.json) file):

```
PM> Update-Database
```

2) In this example, the following user accounts were authorized:
2) Run the application and register the following accounts (the **Register** link). After you register an account, click **Click here to confirm your account**:

```
Email: admin@gmail.com
Expand All @@ -35,27 +35,26 @@
Password: 1*234aD
```

If the current accounts do not exist, go to the **Register** page (`Identity/Account/Register`) to create and confirm these user accounts.
The part of the email before `@` determines user rights (see the table below).

## Example Overview

The [MultiTenantDashboardConfigurator](./CS/BlazorAuth/Code/MultiTenantDashboardConfigurator.cs) class configures user-specific dashboard storage and data providers. It is registered as a scoped DI service in [Program.cs](./CS/BlazorAuth/Program.cs).
In the [Program.cs](./CS/BlazorAuth/Program.cs) file, the application builder calls the [AddDevExpressBlazorDashboard](https://docs.devexpress.com/Dashboard/DevExpress.DashboardBlazor.StartupExtensions.AddDevExpressBlazorDashboard(Microsoft.Extensions.DependencyInjection.IServiceCollection)) method to allow the Dashboard component to process requests in the Blazor circuit. In this file, you can also find custom storage and provider registration (as scoped services).

In [Dashboard.razor](./CS/BlazorAuth/Pages/Dashboard.razor), the component's `OnInitializedAsync` method retrieves the current authentication state and configures the working mode based on the user name. The configurator and each custom store/provider extracts the user name through DI.
The [DashboardUserProvider](./CS/BlazorAuth/Code/DashboardUserProvider.cs) service obtains the current user name from the `AuthenticationStateProvider` ([RevalidatingIdentityAuthenticationStateProvider.cs](./CS/BlazorAuth/Areas/Identity/RevalidatingIdentityAuthenticationStateProvider.cs)). The [MultiTenantDashboardConfigurator](./CS/BlazorAuth/Code/MultiTenantDashboardConfigurator.cs) class and each custom storage and provider obtain the user name from this service.

When the application starts, you see the [Index](./CS/BlazorAuth/Pages/Index.razor) view where you can select a user. Use the **Log in** link for this purpose. Below is a table that illustrates the user IDs and their associated rights in this example:
In [Dashboard.razor](./CS/BlazorAuth/Pages/Dashboard.razor), the `OnInitializedAsync` method specifies the working mode based on the user name.

When the application starts, you see the [Index](./CS/BlazorAuth/Pages/Index.razor) page where you can select a user (the **Log in** link). The table below lists user IDs and their associated rights used within this example:

| Role | Dashboard Storage | DataSource Storage | ConnectionString Provider | DBSchema Provider | Working Mode | Create/Edit |
| --- | --- | --- | --- | --- | --- | --- |
| Admin | dashboard1_admin, dashboard2_admin | SqlDataSource, JsonDataSource | Northwind, CarsXtraScheduling | All (Categories, Products, Cars,...) | Designer, Viewer | Yes |
| Admin | dashboard1_admin, dashboard2_admin | SqlDataSource, JsonDataSource | Northwind, CarsXtraScheduling | All (Categories, Products, Cars,…) | Designer, Viewer | Yes |
| User | dashboard1_user | SqlDataSource | CarsXtraScheduling | Cars | Designer, Viewer | No |
| Guest | dashboard1_guest | - | - | - | ViewerOnly | - |
| Unauthorized | - | - | - | - | ViewerOnly | - |


## Example Details

You can return the following user-specific content:
## Implementation Details

### Dashboards

Expand Down Expand Up @@ -89,19 +88,22 @@

**Files to review**: [CustomConnectionStringProvider.cs](./CS/BlazorAuth/Code/CustomConnectionStringProvider.cs)

### Working Mode

Check warning on line 91 in README.md

View workflow job for this annotation

GitHub Actions / vale

[vale] README.md#L91

[DX.HeadingGerund] Avoid gerunds in headings: 'Working Mode'.
Raw output
{"message": "[DX.HeadingGerund] Avoid gerunds in headings: 'Working Mode'.", "location": {"path": "README.md", "range": {"start": {"line": 91, "column": 5}}}, "severity": "WARNING"}

The Web Dashboard control can operate in `ViewerOnly` mode for unauthorized users. To do this, handle the [DashboardConfigurator.VerifyClientTrustLevel](https://docs.devexpress.com/Dashboard/DevExpress.DashboardWeb.DashboardConfigurator.VerifyClientTrustLevel) event and set the `e.ClientTrustLevel` property to `Restricted`. This setting prevents inadvertent or unauthorized modifications of dashboards stored on a server. You can find more information in the following help section: [Security Considerations - Working Mode Access Rights](https://docs.devexpress.com/Dashboard/118651/web-dashboard/general-information/security-considerations#working-mode-access-rights).
Guests and unauthorized users view dashboards in `ViewerOnly` mode: [Dashboard.razor](./CS/BlazorAuth/Pages/Dashboard.razor) sets the `WorkingMode` property based on the user name. The [DashboardConfigurator.VerifyClientTrustLevel](https://docs.devexpress.com/Dashboard/DevExpress.DashboardWeb.DashboardConfigurator.VerifyClientTrustLevel) event handler in [MultiTenantDashboardConfigurator.cs](./CS/BlazorAuth/Code/MultiTenantDashboardConfigurator.cs) sets the `e.ClientTrustLevel` property to `Restricted` for these users, so they cannot create, edit, or save dashboards on the server. For additional information, refer to the following help sections:

- [Process Dashboard Requests in the Blazor Circuit - Security Considerations](https://docs.devexpress.com/Dashboard/406269/web-dashboard/integrate-dashboard-component/dashboard-component-for-blazor/process-requests-in-blazor-circuit#security-considerations)
- [Security Considerations - Working Mode Access Rights](https://docs.devexpress.com/Dashboard/118651/web-dashboard/general-information/security-considerations#working-mode-access-rights)

**API**: [DashboardConfigurator.VerifyClientTrustLevel Event](https://docs.devexpress.com/Dashboard/DevExpress.DashboardWeb.DashboardConfigurator.VerifyClientTrustLevel)

**Files to review**: [Dashboard.razor](./CS/BlazorAuth/Pages/Dashboard.razor) and [MultiTenantDashboardConfigurator.cs](./CS/BlazorAuth/Code/MultiTenantDashboardConfigurator.cs)

## Documentation

- [Create an ASP.NET Core Dashboard Application](https://docs.devexpress.com/Dashboard/119284/get-started/build-web-dashboard-applications/create-an-aspnet-core-dashboard-application?p=netframework)
- [Process Dashboard Requests in the Blazor Circuit](https://docs.devexpress.com/Dashboard/406269/web-dashboard/integrate-dashboard-component/dashboard-component-for-blazor/process-requests-in-blazor-circuit)
- [Manage Multi-Tenancy](https://docs.devexpress.com/Dashboard/402924/web-dashboard/dashboard-backend/manage-multi-tenancy)
- [ASP.NET Core Blazor authentication and authorization](https://docs.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-5.0)
- [ASP.NET Core Blazor authentication and authorization](https://learn.microsoft.com/en-us/aspnet/core/blazor/security/)

## More Examples

Expand Down
Loading