How to clear all the sessions using ProtectedSessionStorage in blazor server app?

959 Views Asked by At

I am utilizing a Blazor server application in which I have utilized the ProtectedSessionStorage key pair method to store sessions. However, I am facing an issue when it comes to deleting or clearing all the sessions I have stored upon logging out of the application. While there is a way to delete sessions by key, I am seeking a solution to delete all sessions simultaneously.

I have utilized the following code to establish and retrieve sessions, and to date, I have saved a total of 25 sessions. Here is an example of one of the values. However, I am currently attempting to delete these 25 stored values, but I am unsure of how to achieve this.

//set session ProtectedSessionStore.SetAsync("Client", null);

//get session var clientID = await ProtectedSessionStore.GetAsync("Client");

//Delete multiple sessions ???????

2

There are 2 best solutions below

2
Suprabhat Biswal On BEST ANSWER

Since ProtectedSessionStorage lacks the ClearAll() feature, consider invoking a JavaScript method to clear all keys from either localStorage or sessionStorage upon user logout as an alternative.

@inject IJSRuntime jsRuntime 

@code {
    public async ValueTask RemoveAllStorageKeys()
    {
        await jsRuntime.InvokeVoidAsync("removeAllStorageKeys");
    }
}

JS:

<script>
    window.removeAllStorageKeys = () => {
        localStorage.clear(); //remove all keys from localStorage 
        //sessionStorage.clear(); //remove all keys from sessionStorage 
    }
<script>
0
RBee On

There is no Clear method for ProtectedSessionStorage Ms Docs, you are going to have to delete each key manually.

For example, storing a collection of keys in memory and updating it everytime you create a key, then when the user logs out loop through each key and delete it.

HashSet<string> sessionKeys = new(){"Key1","Key2","Client"};
public async Task Logout()
{
    foreach (var key in sessionKeys)
    {
        await ProtectedSessionStore.DeleteAsync(key);
    }
    // Logout user
}