This example demonstrates how to implement authentication based on JWT.
An AccountController generates JWT tokens for the predefined set of users. Once the token is generated, the app saves it to sessionStorage in the Login view.
The Dashboard view passes this token to the CustomDashboardController (it is marked with the AuthorizeAttribute) by using the FetchRemoteService.headers dictionary:
const tokenKey = "accessToken";
function onBeforeRender(sender) {
var dashboardControl = sender;
const token = sessionStorage.getItem(tokenKey);
dashboardControl.remoteService.headers = { "Authorization": "Bearer " + token };
}
Main JWT and Dashboard configurations are defined in the Startup.cs file. We use the IHttpContextAccessor with dependency injection to access the current user name (HttpContext.User.Identity.Name
) in code. Note that you can access it in DashboardConfigurator events and Dashboard storages. Here are corresponding code parts:
// Startup.cs:
var contextAccessor = serviceProvider.GetService<IHttpContextAccessor>();
configurator.DataSourceCacheKeyCreated += (s, e) => {
e.Key.CustomData.Add("LoggedUser", contextAccessor.HttpContext.User.Identity.Name);
};
...
// CustomDashboardStorage.cs:
protected override XDocument LoadDashboard(string dashboardID) {
Debug.WriteLine(сontextAccessor.HttpContext.User.Identity.Name);
return base.LoadDashboard(dashboardID);
}
If you open the Dashboard view without logging in, you see the following error:
- ASP.NET Core Dashboard - How to implement multi-tenant Dashboard architecture
- ASP.NET Core Dashboard - How to load different data based on the current user
- ASP.NET Core Dashboard - How to implement authentication
(you will be redirected to DevExpress.com to submit your response)