How to save user multiple sessions in the redis cache?

56 views Asked by At

I am working on a ASP.NET core application where I am storing a user session inside a Redis cache when the user logs into the system. 'sessionId' serves as the key and 'username' as the value. Now, when the user logs out of the system, I remove the 'sessionId' from the cache. I've received a requirement that when the user changes their password, they should be logged out from all devices.

How can I retrieve all sessions for that specific user from the cache?

If I store 'username' as the key and 'sessionId' as the value, the value will be overridden by the new value. What is the correct way to achieve it?

public async Task<IActionResult> SignIn([FromBody] SignInRequest user)
{
    var sessionId = HttpContext.Session.Id;
    HttpContext.Session.SetString(user.UserName, $"{sessionId}");
    await HttpContext.Session.CommitAsync();

    HttpContext.Session.SetString(user.UserName, $"{sessionId}1");
    await HttpContext.Session.CommitAsync();

    HttpContext.Session.SetString(user.UserName, $"{sessionId}2");
    await HttpContext.Session.CommitAsync();

    var existingSessionData = HttpContext.Session.GetString($"{user.UserName}");

    return Ok();
}
1

There are 1 answers

0
Qiang Fu On

You could still try store 'username' as the key but combine all "sessionId"s to one string as the values.

        public async Task<IActionResult> SignIn([FromBody] SignInRequest user)
        {
            Append(user.UserName, $"{sessionId}");
            Append(user.UserName, $"{sessionId}1");
            Append(user.UserName, $"{sessionId}2");

            var ids=HttpContext.Session.GetString(user.UserName);
            string[] existingSessionData = ids.Trim().Split(" ");   //use trim to delete the first sapce
            return View();
        }

        private async Task Append(string userName,string id)
        {
            var ids=HttpContext.Session.GetString(userName);
            ids = ids + " "+id;                                     //this will also add space when ids is empty
            HttpContext.Session.SetString(userName, ids);
            await HttpContext.Session.CommitAsync();
        }