7 November 2024

Blazor Server, use ProtectedSessionStorage

With the release of ASP.NET Core updates in .NET 5 Preview 8, two new services are available : ProtectedLocalStorage and ProtectedSessionStorage.

Until now I was using the very good library of Chris Sainty : Blazored SessionStorage who did his job perfectly! Now with these new functions available, we will be able to add a grain of security to the variables stored in the browser : 1️⃣ The advantage is that the use is very simple, 2️⃣ your variables will be unreadable and 3️⃣ you will be able to detect when reading them if they have been altered!

Implementation :

First, the project needs to be upgraded to .NET 5 Preview 8 (or more if you read my post in the future 😁).:

1) Upgrade :

  • Microsoft.AspNetCore.* package references → 5.0.0-preview.8.*. or +
  • Microsoft.Extensions.* package references → 5.0.0-preview.8.*. or +
  • System.Net.Http.Json package references → 5.0.0-preview.8.*. or +

2) Then add the Nuget package Microsoft.AspNetCore.Components.ProtectedBrowserStorage

3) Then, in startup.cs to ConfigureServices, add :

services.AddProtectedBrowserStorage();

4) Finally in _Imports.razor, add :

@using Microsoft.AspNetCore.Components.ProtectedBrowserStorage

LocalStorage or SessionStorage

It is as you want but the difference is there according to your need:

Local StorageSession Storage
Capacity10Mb5Mb
Accessible from All tabsCurrent tab
ExpirationNeverWhen closing the tab

In my case I will use SessionStorage :

Store a variable

@inject ProtectedSessionStorage protectedSessionStorage

// HTML code

@code
{
    protected override async Task OnInitializedAsync()
    {
        await protectedSessionStorage.SetAsync("userToken", mytoken);
    }
}

Warning, do not write an int variable directly, it will crash on reading Add .ToString();

Read your variable

@inject ProtectedSessionStorage protectedSessionStorage

// HTML code

@code
{
    protected override async Task OnInitializedAsync()
    {
        ProtectedBrowserStorageResult<string> toto = await protectedSessionStorage.GetAsync<string>("userToken");
        if (toto.Success)
        {
            string mytoken = toto.Value;
        }
        else
        {
        // Kindly ask the user to exit your application
        }
    }
}

variable dans le browser

As you can see, the big advantage is that the variable is unreadable and if it is altered for any reason you can manage your code as you wish.

Leave a Reply