×
iFour Logo

How to store Encrypted Session Data in the Browser?

iFour Team - February 18, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

Sustainable

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.

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

A complete guide on eCommerce conversion rate optimization
A complete guide on eCommerce conversion rate optimization

Table of Content 1. Define your goals 2. Know your target audience 3. Simplified UI/UX design, simple navigation, and high resolution images 4. Design a dedicated landing...

Read More
A comprehensive guide on the Construction management software
A comprehensive guide on the Construction management software

Table of Content 1. Mobile compatibility and inventory management 2. Accurately forecast job costs and monitor them 3. STACK 4. On-premises software is better suited...

Read More
Java And Environment Variables: A Brief Overview
Java And Environment Variables: A Brief Overview

Java is one of many programming languages that have shown much promise in the coding world. With that said, there are many components to consider, when working with Java, including...

Read More