Tuesday, January 23, 2024

Managing Session Integrity in .NET Core Web Applications: A Middleware Approach

 In our journey of developing a .NET Core web application, we encountered a peculiar challenge with our time-tracking feature. The application worked seamlessly in a single tab, but issues arose when users attempted to use it in multiple tabs or windows.

Opening the application in multiple tabs caused the timer to aggregate time across all instances, leading to unexpected behavior. If, for instance, the application was opened in five tabs, it would log 5 minutes instead of the intended 1 minute after 1 minute had passed.

To address this behavior, we aimed to implement a solution that would log out the previous session when more than one instance of the application was opened. We explored various options, including handling it with JavaScript or creating a custom attribute, but ultimately settled on using custom middleware.

Why middleware, you ask? The primary reason is that the middleware's function executes for every request, providing us with a robust solution. So, what did we include in our middleware?

Upon a user's initial login, we store their email and Bearer Token in an SQL table. Subsequent logins generate a new Bearer Token, allowing us to track sessions. The middleware checks the combination of Email and Bearer Token by querying the table. If a record is found, we assume the request is from the same tab. However, if a user logs in from a new tab, a new Bearer Token is generated. Querying the database with this new token results in no rows, prompting us to replace the table entry with the new Bearer Token, thus allowing access to the application.



This middleware-based approach ensures session integrity by handling multiple instances, providing a seamless user experience while maintaining the expected behavior. If a user returns to a previous tab with an expired session, the middleware gracefully handles it by returning a 401 status, effectively logging out the user.

Below is the source code




No comments:

Post a Comment

Managing Session Integrity in .NET Core Web Applications: A Middleware Approach

 In our journey of developing a .NET Core web application, we encountered a peculiar challenge with our time-tracking feature. The applicati...