Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I customize Blazor WebAssembly Msal auth to store token in localStorage instead of sessionStorage?

Context

I am working off the Secure an ASP.NET Core Blazor WebAssembly standalone app with Azure Active Directory B2C guide to enable client-side authentication in my Blazor WebAssembly app (there is no server-side component, the entire app runs in the browser). The setup works as expected, I am able to redirect users to the AD B2C user flow, log in, and redirect back into my app with the user properly authenticated.

Problem

The default authentication behavior persists the JWT token retrieved from AD B2C inside of sessionStorage, which clears as soon as the browser window is closed. I would like to customize this default functionality to instead persist the token to localStorage for longer-lived auth sessions—I'd love to keep the user logged in to subsequent visits after they close the browser window. The docs don't seem to provide any info on how I might accomplish this.

I've also taken a look at the Additional Scenarios docs to under how the RemoteAuthenticatorView might be customized, but was unable to find any info related to how these tokens are stored and retrieved.

I appreciate any guidance on this!

like image 465
Mark Avatar asked Jan 24 '23 22:01

Mark


1 Answers

I have figured it out by browsing the MSAL.js docs: there is a cacheLocation config property that can be set to localStorage, and Microsoft.Authentication.WebAssembly.Msal.Models.MsalProviderOptions exposes that property.

To get it working, I simply added the following to Program.cs:

builder.Services.AddMsalAuthentication(options =>
{
    options.ProviderOptions.Cache.CacheLocation = "localStorage";
    ...
});
like image 69
Mark Avatar answered May 06 '23 04:05

Mark