This post was most recently updated on November 28th, 2021.2 min read.
Let’s make this short and sweet. In this particular case, upgrading a Blazor WASM solution to .NET 6 broke the authentication when deployed to Azure. The same issue could probably happen to a fresh project, though.
This is what you’re running into: If you open your browser console, you’ll see 2 interesting errors – first:
dotnet.6.0.0.o2we6pverp.js:1 mono_wasm_runtime_ready login.microsoftonline.com/common/oauth2/v2.0/token:1 Failed to load resource: the server responded with a status of 400 (Bad Request)
And a moment later, an error along the lines of:
blazor.webassembly.js:1 crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer Unhandled exception rendering component: Cannot read properties of undefined (reading 'toLowerCase') TypeError: Cannot read properties of undefined (reading 'toLowerCase') at u.signInCore (/_content/Microsoft.Authentication.WebAssembly.Msal/AuthenticationService.js:2:193591) at u.getUser (/_content/Microsoft.Authentication.WebAssembly.Msal/AuthenticationService.js:2:191904) Microsoft.JSInterop.JSException: Cannot read properties of undefined (reading 'toLowerCase') TypeError: Cannot read properties of undefined (reading 'toLowerCase')
And perhaps the most annoying is that it only happens in Azure! Locally, everything runs just fine. Another one of those situations when it’s not enough that it runs fine on your machine…
The first error might also contain some nonsense about your app not existing in the tenant, “perhaps you’ve sent your login request to the wrong tenant” and all that – but we know that’s not the case. Although… On a closer look, the tenant id in the error shouldn’t seem familiar at all.
Microsoft forgot to fix a bug in their WebAssembly package size optimizations – Assembly Trimming, namely – and that causes the authentication library to get confused between different tenants, and finally mess up the authentication altogether.
Funnily enough, this has been on their radar at least since .NET 6 Preview 4, as reported in June (see the GitHub link at the end of the article) – but sometimes even the “no-brainer”-looking issues won’t get fixed in time for GA/RTM, for a multitude of reasons.
Anyway, this is how you fix it:
Time needed: 5 minutes.
How to fix Blazor WebAssembly 400 error when authenticating (on .NET 6)?
- Edit your Client-project’s .csproj -file
Just click on the project in Solution Explorer with the right mouse button and select “Edit project file”:
- Add an exclusion for
Add this as a new ItemGroup:
<TrimmerRootAssembly Include="Microsoft.Authentication.WebAssembly.Msal" />
- Remove your “bin” & “obj” folders and rebuild
You should be good!
That should be it. Happy Blazing! 😊
- GitHub issue & discussion about the topic: https://github.com/dotnet/aspnetcore/issues/33312