×

iFour Logo

How to store Encrypted Session Data in the Browser?

Kapil Panchal - February 18, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
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.

 

Table of Content

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:


                

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;
              

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

Example

@inject ProtectedSessionStorage storage 
              

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("greeting");            

              

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)  
{  
 
} @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("NewsAlert.showAlert");  
    bool oldValue = showAlert;  
showAlert = result.Success ? result.Value : true;  
    if (showAlert != oldValue)  
    {  
StateHasChanged();  
    }  
}              

                    

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);  
}       
                  

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(); } } }
                  

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.

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.   Table of Content 1. What’s the difference between localStorage and sessionStorage? 2. Security Implication of using browser storage 3. How can we use session Storage in Blazor Server? 4. Example - Breaking News Control 5. Conclusion 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: 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; You can add the following line at the top of your Blazor Component. Example @inject ProtectedSessionStorage storage 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("greeting"); 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) { @Text× } @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("NewsAlert.showAlert"); bool oldValue = showAlert; showAlert = result.Success ? result.Value : true; if (showAlert != oldValue) { StateHasChanged(); } } 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. See here 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); } 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(); } } } 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.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

Power Apps vs Power Automate: When to Use What?
Power Apps vs Power Automate: When to Use What?

I often see people asking questions like “Is Power App the same as Power Automate?”. “Are they interchangeable or have their own purpose?”. We first need to clear up this confusion...

Azure DevOps Pipeline Deployment for Competitive Business: The Winning Formula
Azure DevOps Pipeline Deployment for Competitive Business: The Winning Formula

We always hear about how important it is to be competitive and stand out in the market. But as an entrepreneur, how would you truly set your business apart? Is there any way to do...

React 18 Vs React 19: Key Differences To Know For 2024
React 18 Vs React 19: Key Differences To Know For 2024

Ever wondered how a simple technology can spark a revolution in the IT business? Just look at React.js - a leading Front-end JS library released in 2013, has made it possible. Praised for its seamless features, React.js has altered the way of bespoke app development with its latest versions released periodically. React.js is known for building interactive user interfaces and has been evolving rapidly to meet the demands of modern web development. Thus, businesses lean to hire dedicated React.js developers for their projects. React.js 19 is the latest version released and people are loving its amazing features impelling them for its adoption.