DEV Community

Cover image for How to store Encrypted Session Data in the Browser?
Harshal Suthar
Harshal Suthar

Posted on • Originally published at ifourtechnolab.com

How to store Encrypted Session Data in the Browser?

When you are developing the websites with JavaScript, you can use the localStorage and sessionStorage. In the localStorage and sessionStorage, the data stores in key-value pair in the user’s web browser. It is also known as sandboxed for each website, you can access only your data store on every website, and you can’t access to localStorage and sessionStorage objects being saved from another website.

The data stores carefully because this data is volatile. Volatile means not permanent storage and it’s never guaranteed to be there. Your browser can decide to delete this data or the user can use a PC clean-up tool and all stored data will be gone.

What’s the difference between localStorage and sessionStorage?

There are only two differences between localStorage and sessionStorage.

  • The sessionStorage data only exists when the browser tab is open, if the user closes the tab or exists their web browser your sessionStorage data is cleared.
  • localStorage holds the data until cleared by the browser or some user action.

Security Implication of using browser storage

This is very important to note that even though this data is sandboxed,it stores your sensitive data in the browser can lead to many vulnerabilities. Anyone can add third-party libraries into your website, so your website is a sufferer of an XSS (Cross-Site-Scripting) attack.

Example:

<script src="“https://websiteExample.com/somelibrary.js”"></script>
Enter fullscreen mode Exit fullscreen mode

The attacker could be added malicious javascript to the library to receive data from localStorage and sessionStorage and send it to the server.

The browser security has implications of using localStorage are debated, we will use sessionStorage in this blog. The session storage data is considered the secure data. If your session ends your data is automatically deleted.

How can we use session Storage in Blazor Server?

In.NET 5, the Visual Studio can add many features of Blazor Server and BlazorWebAssembly. There are two new classes add in the Blazor Server and BlazorWebAssembly.

  • ProtectedLocalStorage
  • ProtectedSessionStorage

Both classes are provided to client-side sessionStorage and localStorage from our server-side C# code. These classes are very useful and easy to use for the developer, these classes are encrypted the data instead of storing of plaintext.

First of all, we must import the class (either in our _Imports.razor file or in the component itself.)

Example

@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;

Enter fullscreen mode Exit fullscreen mode

You can add the following line at the top of your Blazor Component.

Example

@inject ProtectedSessionStorage storage 

Enter fullscreen mode Exit fullscreen mode

It will tell the dependency injection service to give us a ProtectedSessionStorage instance.

After you can write the SetAsync() method and GetAsync() method, so you can easily data get of these methods.

Example

// Set   
await storage.SetAsync("greeting", "Hello, World!");  
// Get  
var greeting = await storage.GetAsync<string>("greeting");            
</string>

Enter fullscreen mode Exit fullscreen mode

Read More: Introduction To C# 9

Example - Breaking News Control

In this example, we have discussed a news alert that appears at the top of the page with any breaking news. If the user can dismiss this banner, and it is dismissed, it will not display again during this session. It is the perfect example of session storage because we want the banner to stay dismissed until the next time the user opens your web app.

First of all, we have created a new Blazor Component and give the named ToastAlert and type the below code.

Example


@if (showAlert)  
{  

Enter fullscreen mode Exit fullscreen mode

} @code { private bool showAlert = false; [Parameter] public string Text { get; set; } = string.Empty; private async Task OnDismiss() { showAlert = false; } }
It is the basis for our component. There are the following requirements we need to create for function.

If the component is loaded, we have to check to sessionStorage to see if the alert has ever been dismissed. If it hasn’t, then it is shown.
If the user dismisses the alert box, so we have to store that data in sessionStorage for the next time the component loaded during this session.
The component has been loaded with the sessionStorage.

Example


protected override async Task OnAfterRenderAsync(bool firstRender)  
{  
    var result = await storage.GetAsync<bool>("NewsAlert.showAlert");  
    bool oldValue = showAlert;  
showAlert = result.Success ? result.Value : true;  
    if (showAlert != oldValue)  
    {  
StateHasChanged();  
    }  
}              
</bool>


Enter fullscreen mode Exit fullscreen mode

The following method will describe below:

Firstly, we have called the bool value for NewsAlert.showAlert in sessionStorage.
After we have copied the value of the showAlert value so that later we can check if it changed.
Set the value of showAlert. This value is a pass with a key, then set it to that value. This value is by default set to true.
If the value has been changed, the StateHasChanged() method is called. The Blazor changes the value of the component state.
The StateHasChanged() method can potentially force the entire component to redraw, so be mindful about its usage. As a general rule of thumb, you should never call this method explicitly, but since we change the state immediately after creating the component, it won't update the state unless we call it. The Blazor didn't like it when we did JS interop in OnInitializedAsync(). There is a special runtime error when you do it, that says to use OnAfterRender instead.

One Stop Solution for ASP.Net Software Development ? Enquire Today.

Now finally we need to update sessionStorage when the user dismisses the alert,

Example

private async Task OnDismiss()  
{  
showAlert = false;  
await storage.SetAsync("NewsAlert.showAlert", false);  
}       

Enter fullscreen mode Exit fullscreen mode

Example

@inject ProtectedSessionStorage storage  

@if (showAlert)  
{  }
@code { private bool showAlert = false;
[Parameter] public string Text { get; set; } = string.Empty; private async Task OnDismiss() { showAlert = false; await storage.SetAsync("NewsAlert.showAlert", false); } protected override async Task OnAfterRenderAsync(bool firstRender) { var result = await storage.GetAsync("NewsAlert.showAlert"); bool oldValue = showAlert; showAlert = result.Success ? result.Value : true; if (showAlert != oldValue) { StateHasChanged(); } } }

Enter fullscreen mode Exit fullscreen mode

Conclusion

In this blog, we have discussed about the client-side browser storage can prove useful in your project. If your data is stored in the localStorage so your data is not secure on this website and you can always store the data in sessionStorage.

Top comments (0)