diff --git a/CS/BlazorAuth/BlazorAuth.csproj b/CS/BlazorAuth/BlazorAuth.csproj index 75744e0..0c92673 100644 --- a/CS/BlazorAuth/BlazorAuth.csproj +++ b/CS/BlazorAuth/BlazorAuth.csproj @@ -4,18 +4,17 @@ net10.0 enable enable - aspnet-BlazorAuth-FEB431D8-D991-4F8A-923F-40225A99A530 - - - - - - - - - + + + + + + + + + \ No newline at end of file diff --git a/CS/BlazorAuth/Code/AuthHelper.cs b/CS/BlazorAuth/Code/AuthHelper.cs new file mode 100644 index 0000000..4dde826 --- /dev/null +++ b/CS/BlazorAuth/Code/AuthHelper.cs @@ -0,0 +1,18 @@ +using Microsoft.AspNetCore.Components.Authorization; + +namespace BlazorAuth { + public static class AuthHelper { + internal static string? GetUserName(AuthenticationStateProvider provider) { + var stateTask = provider.GetAuthenticationStateAsync(); + + if (!stateTask.IsCompletedSuccessfully) + throw new InvalidOperationException("Authentication state is not ready."); + + var identity = stateTask.GetAwaiter().GetResult().User.Identity; + + return identity?.IsAuthenticated == true + ? identity.Name?.Split('@')[0] + : null; + } + } +} \ No newline at end of file diff --git a/CS/BlazorAuth/Code/CustomConnectionStringProvider.cs b/CS/BlazorAuth/Code/CustomConnectionStringProvider.cs index fe1e727..08e05b8 100644 --- a/CS/BlazorAuth/Code/CustomConnectionStringProvider.cs +++ b/CS/BlazorAuth/Code/CustomConnectionStringProvider.cs @@ -1,19 +1,19 @@ using DevExpress.DataAccess.ConnectionParameters; using DevExpress.DataAccess.Web; -using System.Collections.Generic; namespace BlazorAuth { public class CustomConnectionStringProvider : IDataSourceWizardConnectionStringsProvider { - private string userName; - private Dictionary connectionStrings = new Dictionary(); + readonly IDashboardUserProvider dashboardUserProvider; + readonly Dictionary connectionStrings = new Dictionary(); - public CustomConnectionStringProvider(string userName) { - this.userName = userName; + public CustomConnectionStringProvider(IDashboardUserProvider dashboardUserProvider) { + this.dashboardUserProvider = dashboardUserProvider; connectionStrings.Add("NorthwindConnectionString", @"XpoProvider=SQLite; Data Source=App_Data/nwind.db;"); connectionStrings.Add("CarsXtraSchedulingConnectionString", @"XpoProvider=SQLite;Data Source=App_Data/CarsDB.db;"); } public Dictionary GetConnectionDescriptions() { + var userName = dashboardUserProvider.GetUserName(); var connections = new Dictionary(); if (userName == "admin") { diff --git a/CS/BlazorAuth/Code/CustomDBSchemaProvider.cs b/CS/BlazorAuth/Code/CustomDBSchemaProvider.cs index ee5e368..0661ea2 100644 --- a/CS/BlazorAuth/Code/CustomDBSchemaProvider.cs +++ b/CS/BlazorAuth/Code/CustomDBSchemaProvider.cs @@ -1,25 +1,24 @@ using DevExpress.DataAccess.Sql; using DevExpress.Xpo.DB; -using Microsoft.AspNetCore.Http; -using System.Linq; namespace BlazorAuth { public class CustomDBSchemaProvider : DBSchemaProviderEx { - private string userName; + private readonly IDashboardUserProvider dashboardUserProvider; - public CustomDBSchemaProvider(string userName) : base() { - this.userName = userName; + public CustomDBSchemaProvider(IDashboardUserProvider dashboardUserProvider) : base() { + this.dashboardUserProvider = dashboardUserProvider; } public override DBTable[] GetTables(SqlDataConnection connection, params string[] tableList) { var result = base.GetTables(connection, tableList); + var userName = dashboardUserProvider.GetUserName(); if (userName == "admin") { return result; } else if (userName == "user") { return result.Where(t => t.Name == "Cars").ToArray(); } else { - return new DBTable[0]; + return []; } } } diff --git a/CS/BlazorAuth/Code/CustomDashboardStorage.cs b/CS/BlazorAuth/Code/CustomDashboardStorage.cs index 319189a..0e30271 100644 --- a/CS/BlazorAuth/Code/CustomDashboardStorage.cs +++ b/CS/BlazorAuth/Code/CustomDashboardStorage.cs @@ -1,29 +1,28 @@ -using DevExpress.DashboardWeb; -using Microsoft.AspNetCore.Hosting; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Xml.Linq; +using System.Xml.Linq; +using DevExpress.DashboardWeb; +using DevExpress.Security; namespace BlazorAuth { public class CustomDashboardStorage : IEditableDashboardStorage { - private string userName; - private string dashboardStorageFolder; + readonly IDashboardUserProvider dashboardUserProvider; + string DashboardStorageFolder { get; } - public CustomDashboardStorage(IWebHostEnvironment hostingEnvironment, string userName) { - this.userName = userName; - this.dashboardStorageFolder = hostingEnvironment.ContentRootFileProvider.GetFileInfo("App_Data/Dashboards").PhysicalPath; + 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."); } public IEnumerable GetAvailableDashboardsInfo() { + var userName = dashboardUserProvider.GetUserName(); var dashboardInfos = new List(); - var files = Directory.GetFiles(dashboardStorageFolder, "*.xml"); + var files = Directory.GetFiles(DashboardStorageFolder, "*.xml"); - foreach (var item in files) { + foreach(var item in files) { var name = Path.GetFileNameWithoutExtension(item); - if (!string.IsNullOrEmpty(userName) && name.EndsWith(userName, System.StringComparison.InvariantCultureIgnoreCase)) + if(!string.IsNullOrEmpty(userName) && name.EndsWith(userName, System.StringComparison.InvariantCultureIgnoreCase)) dashboardInfos.Add(new DashboardInfo() { ID = name, Name = name }); } @@ -31,9 +30,11 @@ public IEnumerable GetAvailableDashboardsInfo() { } public XDocument LoadDashboard(string dashboardID) { - if (GetAvailableDashboardsInfo().Any(di => di.Name == dashboardID)) { - var path = Path.Combine(dashboardStorageFolder, dashboardID + ".xml"); - var content = File.ReadAllText(path); + if(GetAvailableDashboardsInfo().Any(di => di.Name == dashboardID)) { + var dashboardPath = Path.GetFullPath(Path.Combine(DashboardStorageFolder, dashboardID + ".xml")); + ValidateDashboardPath(dashboardPath); + + var content = File.ReadAllText(dashboardPath); return XDocument.Parse(content); } else { throw new System.ApplicationException("You are not authorized to view this dashboard."); @@ -41,23 +42,34 @@ public XDocument LoadDashboard(string dashboardID) { } public string AddDashboard(XDocument dashboard, string dashboardName) { - if (string.IsNullOrEmpty(userName) || userName != "admin") + var userName = dashboardUserProvider.GetUserName(); + + if(string.IsNullOrEmpty(userName) || userName != "admin") throw new System.ApplicationException("You are not authorized to add dashboards."); - var path = Path.Combine(dashboardStorageFolder, dashboardName + "_" + userName + ".xml"); + var dashboardPath = Path.GetFullPath(Path.Combine(DashboardStorageFolder, dashboardName + "_" + userName + ".xml")); + ValidateDashboardPath(dashboardPath); - File.WriteAllText(path, dashboard.ToString()); + File.WriteAllText(dashboardPath, dashboard.ToString()); - return Path.GetFileNameWithoutExtension(path); + return Path.GetFileNameWithoutExtension(dashboardPath); } public void SaveDashboard(string dashboardID, XDocument dashboard) { - if (string.IsNullOrEmpty(userName) || userName != "admin") + var userName = dashboardUserProvider.GetUserName(); + + if(string.IsNullOrEmpty(userName) || userName != "admin") throw new System.ApplicationException("You are not authorized to save dashboards."); - var path = Path.Combine(dashboardStorageFolder, dashboardID + ".xml"); + var dashboardPath = Path.GetFullPath(Path.Combine(DashboardStorageFolder, dashboardID + ".xml")); + ValidateDashboardPath(dashboardPath); + + File.WriteAllText(dashboardPath, dashboard.ToString()); + } - File.WriteAllText(path, dashboard.ToString()); + void ValidateDashboardPath(string dashboardPath) { + if(!SafePath.IsRooted(DashboardStorageFolder, dashboardPath)) + throw new InvalidOperationException("Invalid dashboard folder dashboardPath"); } } } \ No newline at end of file diff --git a/CS/BlazorAuth/Code/CustomDataSourceStorage.cs b/CS/BlazorAuth/Code/CustomDataSourceStorage.cs index 13aa0ae..bf7044e 100644 --- a/CS/BlazorAuth/Code/CustomDataSourceStorage.cs +++ b/CS/BlazorAuth/Code/CustomDataSourceStorage.cs @@ -1,22 +1,20 @@ -using DevExpress.DashboardCommon; +using System.Xml.Linq; +using DevExpress.DashboardCommon; using DevExpress.DashboardWeb; using DevExpress.DataAccess.Json; using DevExpress.DataAccess.Sql; -using System.Collections.Generic; -using System.Linq; -using System.Xml.Linq; namespace BlazorAuth { public class CustomDataSourceStorage : IDataSourceStorage { - private string userName; - private Dictionary documents = new Dictionary(); + readonly IDashboardUserProvider dashboardUserProvider; + readonly Dictionary documents = new Dictionary(); - private const string sqlDataSourceId1 = "SQL Data Source (Northwind)"; - private const string sqlDataSourceId2 = "SQL Data Source (CarsXtraScheduling)"; - private const string jsonDataSourceId = "JSON Data Source"; + const string sqlDataSourceId1 = "SQL Data Source (Northwind)"; + const string sqlDataSourceId2 = "SQL Data Source (CarsXtraScheduling)"; + const string jsonDataSourceId = "JSON Data Source"; - public CustomDataSourceStorage(string userName) { - this.userName = userName; + public CustomDataSourceStorage(IDashboardUserProvider dashboardUserProvider) { + this.dashboardUserProvider = dashboardUserProvider; DashboardSqlDataSource sqlDataSource1 = new DashboardSqlDataSource(sqlDataSourceId1, "NorthwindConnectionString"); SelectQuery query1 = SelectQueryFluentBuilder @@ -47,7 +45,7 @@ public CustomDataSourceStorage(string userName) { } public XDocument GetDataSource(string dataSourceID) { - if (GetDataSourcesID().Contains(dataSourceID)) { + if(GetDataSourcesID().Contains(dataSourceID)) { return documents[dataSourceID]; } else { throw new System.ApplicationException("You are not authorized to use this datasource."); @@ -55,12 +53,14 @@ public XDocument GetDataSource(string dataSourceID) { } public IEnumerable GetDataSourcesID() { - if (userName == "admin") { + var userName = dashboardUserProvider.GetUserName(); + + if(userName == "admin") { return documents.Keys; - } else if (userName == "user") { - return new string[] { sqlDataSourceId2 }; + } else if(userName == "user") { + return [sqlDataSourceId2]; } else { - return new string[0]; + return []; } } } diff --git a/CS/BlazorAuth/Code/DashboardUserProvider.cs b/CS/BlazorAuth/Code/DashboardUserProvider.cs new file mode 100644 index 0000000..5a37719 --- /dev/null +++ b/CS/BlazorAuth/Code/DashboardUserProvider.cs @@ -0,0 +1,35 @@ +using Microsoft.AspNetCore.Components.Authorization; + +namespace BlazorAuth { + public interface IDashboardUserProvider { + Task GetUserNameAsync(); + string? GetUserName(); + } + + public class DashboardUserProvider : IDashboardUserProvider { + readonly AuthenticationStateProvider authProvider; + + public DashboardUserProvider(AuthenticationStateProvider provider) { + this.authProvider = provider; + } + + public string? GetUserName() { + var stateTask = authProvider.GetAuthenticationStateAsync(); + if(!stateTask.IsCompletedSuccessfully) + throw new InvalidOperationException("Authentication state is not ready."); + + return ReadName(stateTask.Result); + } + + public async Task GetUserNameAsync() { + var state = await authProvider.GetAuthenticationStateAsync(); + + return ReadName(state); + } + + static string? ReadName(AuthenticationState state) { + var identity = state.User.Identity; + return identity?.IsAuthenticated == true ? identity.Name?.Split('@')[0] : null; + } + } +} \ No newline at end of file diff --git a/CS/BlazorAuth/Code/MultiTenantDashboardConfigurator.cs b/CS/BlazorAuth/Code/MultiTenantDashboardConfigurator.cs index e15ea10..6a8ff02 100644 --- a/CS/BlazorAuth/Code/MultiTenantDashboardConfigurator.cs +++ b/CS/BlazorAuth/Code/MultiTenantDashboardConfigurator.cs @@ -1,23 +1,27 @@ using DevExpress.DashboardWeb; +using DevExpress.DataAccess.Sql; +using DevExpress.DataAccess.Web; namespace BlazorAuth { public class MultiTenantDashboardConfigurator : DashboardConfigurator { - private string? userName; + public MultiTenantDashboardConfigurator( + IDashboardUserProvider dashboardUserProvider, + IDataSourceWizardConnectionStringsProvider connectionStringsProvider, + IDataSourceStorage dataSourceStorage, + IEditableDashboardStorage dashboardStorage, + IDBSchemaProviderEx dbSchemaProvider) { - public MultiTenantDashboardConfigurator(IWebHostEnvironment hostingEnvironment, IHttpContextAccessor contextAccessor) { - string? identityName = contextAccessor.HttpContext?.User.Identity?.Name; - userName = identityName?.Substring(0, identityName.IndexOf("@")); + SetConnectionStringsProvider(connectionStringsProvider); + SetDataSourceStorage(dataSourceStorage); + SetDashboardStorage(dashboardStorage); + SetDBSchemaProvider(dbSchemaProvider); - SetConnectionStringsProvider(new CustomConnectionStringProvider(userName)); - SetDataSourceStorage(new CustomDataSourceStorage(userName)); - SetDashboardStorage(new CustomDashboardStorage(hostingEnvironment, userName)); - SetDBSchemaProvider(new CustomDBSchemaProvider(userName)); + VerifyClientTrustLevel += (s, e) => { + var userName = dashboardUserProvider.GetUserName(); - VerifyClientTrustLevel += MultiTenantDashboardConfigurator_VerifyClientTrustLevel; - } - private void MultiTenantDashboardConfigurator_VerifyClientTrustLevel(object sender, VerifyClientTrustLevelEventArgs e) { - if (string.IsNullOrEmpty(userName) || userName == "guest") - e.ClientTrustLevel = ClientTrustLevel.Restricted; + if (string.IsNullOrEmpty(userName) || userName == "guest") + e.ClientTrustLevel = ClientTrustLevel.Restricted; + }; } } } \ No newline at end of file diff --git a/CS/BlazorAuth/Controllers/DefaultDashboardController.cs b/CS/BlazorAuth/Controllers/DefaultDashboardController.cs deleted file mode 100644 index b6c1b4f..0000000 --- a/CS/BlazorAuth/Controllers/DefaultDashboardController.cs +++ /dev/null @@ -1,11 +0,0 @@ -using DevExpress.DashboardAspNetCore; -using DevExpress.DashboardWeb; -using Microsoft.AspNetCore.DataProtection; - -namespace BlazorAuth.Controllers { - public class DefaultDashboardController : DashboardController { - public DefaultDashboardController(DashboardConfigurator configurator, IDataProtectionProvider? dataProtectionProvider = null) - : base(configurator, dataProtectionProvider) { - } - } -} \ No newline at end of file diff --git a/CS/BlazorAuth/Pages/Dashboard.razor b/CS/BlazorAuth/Pages/Dashboard.razor index 35a868c..50c5dd2 100644 --- a/CS/BlazorAuth/Pages/Dashboard.razor +++ b/CS/BlazorAuth/Pages/Dashboard.razor @@ -1,19 +1,14 @@ @page "/dashboard" -@inject AuthenticationStateProvider AuthStateProvider +@inject IDashboardUserProvider DashboardUserProvider - - + @code { private WorkingMode workingMode; protected override async Task OnInitializedAsync() { - AuthenticationState authState = await AuthStateProvider.GetAuthenticationStateAsync(); - if (authState.User.Identity is not null) { - var identityName = authState.User.Identity.Name; - var userName = identityName?.Substring(0, identityName.IndexOf("@")); + var userName = await DashboardUserProvider.GetUserNameAsync(); - workingMode = (userName == "admin" || userName == "user") ? WorkingMode.Designer : WorkingMode.ViewerOnly; - } + workingMode = (userName == "admin" || userName == "user") ? WorkingMode.Designer : WorkingMode.ViewerOnly; } } \ No newline at end of file diff --git a/CS/BlazorAuth/Program.cs b/CS/BlazorAuth/Program.cs index 44d4f1e..371f781 100644 --- a/CS/BlazorAuth/Program.cs +++ b/CS/BlazorAuth/Program.cs @@ -2,8 +2,10 @@ using BlazorAuth.Areas.Identity; using BlazorAuth.Data; using DevExpress.AspNetCore; -using DevExpress.DashboardAspNetCore; +using DevExpress.DashboardBlazor; using DevExpress.DashboardWeb; +using DevExpress.DataAccess.Sql; +using DevExpress.DataAccess.Web; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; @@ -16,21 +18,25 @@ // Add services to the container. builder.Services.AddDbContext(options => - options.UseSqlServer( - configuration.GetConnectionString("DefaultConnection"))); + options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"))); builder.Services.AddDefaultIdentity(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores(); builder.Services.AddDevExpressControls(); builder.Services.AddRazorPages(); -builder.Services.AddHttpContextAccessor(); - +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddServerSideBlazor(); builder.Services.AddScoped>(); builder.Services.AddDatabaseDeveloperPageExceptionFilter(); +builder.Services.AddDevExpressBlazorDashboard(); + var app = builder.Build(); // Configure the HTTP request pipeline. @@ -47,13 +53,11 @@ app.UseStaticFiles(); app.UseDevExpressControls(); app.UseRouting(); -app.MapDashboardRoute("api/dashboard", "DefaultDashboard"); app.UseAuthentication(); app.UseAuthorization(); -app.MapControllers(); app.MapBlazorHub(); app.MapFallbackToPage("/_Host"); -app.Run(); +app.Run(); \ No newline at end of file diff --git a/README.md b/README.md index fc38f89..fa26364 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ -![](https://img.shields.io/endpoint?url=https://codecentral.devexpress.com/api/v1/VersionRange/390294928/26.1.5%2B) +![](https://img.shields.io/endpoint?url=https://codecentral.devexpress.com/api/v1/VersionRange/390294928/26.2.1%2B) [![](https://img.shields.io/badge/Open_in_DevExpress_Support_Center-FF7200?style=flat-square&logo=DevExpress&logoColor=white)](https://supportcenter.devexpress.com/ticket/details/T1017576) [![](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) @@ -8,7 +8,7 @@ This example shows how to configure the Dashboard component for Blazor so that it works in the multi-user environment. -You can identify a user in the ASP.NET Core's `HttpContext.User` and return the user-specific content. +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. ![](web-dashboard-blazor-auth.png) @@ -16,7 +16,7 @@ You can identify a user in the ASP.NET Core's `HttpContext.User` and return the 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: -1) Apply the `00000000000000_CreateIdentitySchema` migration to the `aspnet-BlazorAuth-9F8F37E8-C7E8-4D29-BFE6-47204A65FA44` database. You can run the following command in the Package Manager Console for this purpose: +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: ``` PM> Update-Database @@ -39,7 +39,9 @@ If the current accounts do not exist, go to the **Register** page (`Identity/Acc ## Example Overview -You can limit access to sensitive information depending on the current user's ID. The [MultiTenantDashboardConfigurator](./CS/BlazorAuth/Code/MultiTenantDashboardConfigurator.cs) class is an entry point for configuring all providers. Every custom store/provider reads the `IHttpContextAccessor.HttpContext.User.Identity`. In the `MultiTenantDashboardConfigurator` class, use the standard [IHttpContextAccessor](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-context) with dependency injection to access the HTTP context and pass the retrieved user name to Dashboard providers listed above. This class is registered as a *scoped* DI service in the [Program.cs](./CS/BlazorAuth/Program.cs) file. +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 [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. 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: