Asp net mvc 5 gmail like logout from all devices and active sessions

Introduction

ASP.NET is a popular language used for building web applications. In this article, we will discuss how to a Gmail-like logout functionality in an ASP.NET MVC 5 application. This feature allows to log out from all devices and sessions.

Implementation

To implement this functionality, we need to store the active sessions and devices associated with each user. We can this by a database table to store the session information.

First, let's create a table in the database to store the session information. We can use the following SQL script to create the table:


CREATE TABLE UserSessions (
    UserId INT,
    SessionId VARCHAR(255),
    DeviceId VARCHAR(255),
    LastActivityTime DATETIME
);

Next, we need to modify the login and logout functionality in our ASP.NET MVC 5 application to handle the session management. When a user logs in, we need to insert a new record into the UserSessions table with the user's ID, session ID, device ID, and the current time.

Here is an example of how to insert a new session record in the login :


public ActionResult Login(LoginViewModel model)
{
    // Perform login logic

    // Insert session record
    using (var db = new ApplicationDbContext())
    {
        var session = new UserSession
        {
            UserId = user.Id,
            SessionId = Session.SessionID,
            DeviceId = GetDeviceId(),
            LastActivityTime = DateTime.Now
        };

        db.UserSessions.Add(session);
        db.();
    }

    // Redirect to home page
    return RedirectToAction("Index", "Home");
}

Now, let's move on to the logout functionality. When a user clicks on the “Logout from all devices” button, we need to delete all session records associated with the user from the UserSessions table.

Here is an example of how to delete session records in the logout action:


public ActionResult Logout()
{
    // Delete session records
    using (var db = new ApplicationDbContext())
    {
        var userId = User.Identity.GetUserId();
        var sessions = db.UserSessions.Where(s => s.UserId == userId).ToList();

        db.UserSessions.RemoveRange(sessions);
        db.SaveChanges();
    }

    // Perform logout logic

    // Redirect to login page
    return RedirectToAction("Login", "Account");
}

Conclusion

In this article, we have discussed how to implement a Gmail-like logout functionality in an ASP.NET MVC 5 application. By storing session information in a database table and it during login and logout actions, we can users with the ability to log out from all devices and active sessions. This feature enhances the security and user experience of our web application.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents