This is a short post demonstrating how the Auth0 embedded Lock widget can be used with client-side Blazor. The code for this example is on Github.
I thought I'd try out integrating Auth0's embedded lock, which as far as I can tell is only available via their JS library. This was just a short experiment and not all of the features you'd want are implemented (and the code can no doubt be improved quite a bit) - but what's there is working, allows you to login/logout using the embedded lock widget and also silently renews when the application starts up if the token is still valid.
I didn't have to write too much code to get this working. I started with the default hosted (client-side) Blazor template created from 'New Project..' inside Visual Studio.
It gives us the standard 3 project split with Client, Server and Shared projects. All of the following work is done inside the Client project.
I had to add some packages via Nuget for the code below - here they are:
First up is some JS code, borrowing from code I used in one of my previous posts. I put this into a js folder under wwwroot.
Then I link to this and the Auth0 libraries we need in our index.html file.
Then I created an Auth0Service class, under a Services folder:
The Auth0Service class first initialises the lock widget, calling the init function in our JS code. It then checks to see if the user already has a valid session and if so attempts to renew the token silently. There are also some methods which are invoked from our JS code (they have the [JsInvokable] attribute) which handle login or token renew success or failures.
And an AppState class, which we'll be injecting into our Blazor components and which expose our login/logout methods:
Modifying existing code in the MainLayout.cshtml & Startup.cs files:
And finally, I had to add a Linker definition in order to get the JSON deserialization to work - which required a Linker.xml file and definition in the csproj file:
And that's it. I hope you found this useful, and please feel free to get in touch with any comments or questions.