×

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.

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. 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.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

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
How to Build a Tech Startup from Scratch with Online Business Education
How to Build a Tech Startup from Scratch with Online Business Education

Imagine having lofty ambitions to create your own software development company but having no idea where to begin. That's exactly how current tech giants had felt when they were to start their own businesses. They were aware of their amazing ideas, but they needed assistance or motivation to implement them. However, as the generation evolved, the difficulties diminished and a variety of chances to study and find a solution on one's own emerged.

How mobile apps are transforming the Education sector?
How mobile apps are transforming the Education sector?

Just less than a year before children in many parts of the world were taking distant classes from their teachers instead of going to school. The menace of the Covid pandemic made a...

How IoT is transforming the Education industry in 2022?
How IoT is transforming the Education industry in 2022?

Learning is the process of acquiring new knowledge, skills, values, or behavior. It typically takes place in a school or educational institution but also increasingly can happen online....