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 Dasard view passes this token to the CustomDasardController (it is marked with the AuthorizeAttribute) by using the AjaxRemoteService.headers dictionary:
const tokenKey = "accessToken";
function onBeforeRender(sender) {
var dasardControl = sender;
const token = sessionStorage.getItem(tokenKey);
dasardControl.remoteService.headers = { "Authorization": "Bearer " + token };
}
Main JWT and Dasard 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 DasardConfigurator events and Dasard storages. Here are corresponding code parts:
// Startup.cs:
var contextAccessor = serviceProvider.GetService<IHttpContextAccessor>();
configurator.CustomParameters += (s, e) => {
e.Parameters.Add(new DasardParameter("LoggedUser", typeof(string), contextAccessor.HttpContext.User.Identity.Name));
};
...
// CustomDasardStorage.cs:
protected override XDocument LoadDasard(string dasardID) {
Debug.WriteLine(сontextAccessor.HttpContext.User.Identity.Name);
return base.LoadDasard(dasardID);
}
If you open the Dasard view without logging in, you see the following error:
- ASP.NET Core Dasard - How to implement multi-tenant Dasard architecture
- ASP.NET Core Dasard - How to load different data based on the current user
- ASP.NET Core Dasard - How to implement authentication
(you will be redirected to DevExpress.com to submit your response)