.NET 5 Web API + Blazor w/ Auth0 JWT & cookie authentication
TL;DR: here's a repo that demonstrates .NET 5 WebAPI + Blazor + Auth0: https://github.com/jsauve/WebApiPlusBlazorWithAuth0JwtAndCookies
In my spare time, I've been working on a Xamarin-based mobile app for my local arts & music community, for the last 18 months or so. Of course the pandemic has put the brakes on any kind of gatherings such as live music and art shows, but I continue to work on the app in the meantime in the hopes that it can serve the community when the world begins to emerge from lockdowns.
Since day one of development, a .NET-based Web API has been providing the data for the app. It started out as a .NET Core 3.0 app, and continued to evolve as the .NET framework has evolved. Today, it is a .NET 5 -based Web API project.
Although most of the data in the mobile app is available to users without them needing to authenticate in any way (it's an app for public community events), some features do require a login, such as saving favorite events or submitting new events to the system. I hold the belief that identity management is a difficult task best left to those who have done it well, such as Google, Facebook, Twitter, etc. For that reason, I never bother to write my own user account system; it's too cumbersome and difficult to do securely and correctly. But I also don't want to constrain my users to any single specific identity provider. That's why I use Auth0.
Auth0 provides a single API and interface through which to authenticate users to your app, using your choice of the leading identity providers. Auth0 rides on top of industry standard authentication protocols and mechanisms like OAuth2 and OpenID Connect. They have solutions for a variety of platforms, including ASP.NET and Xamarin.
When your mobile app makes calls against your API, the generally accepted modern strategy for this is to use JWT tokens. This is how I verify that users in my app have access to my non-public API endpoints.
I recently decided to add a Blazor web app to my solution in order to perform admin data management. I also decided to add this Blazor app to the same project as my Web API app. This means that both can run side-by-side in a single hosting instance.
However, because Web API is best suited to JWT authentication and Blazor is best suited to cookie authentication, getting Auth0 properly configured was a challenge. It turns out that it's not anything special that needs to happen with Auth0 itself, but with the authentication settings of ASP.NET and the extensions that it uses.
It was an interesting challenge to solve, and I figure there will be other developers trying to achieve the same goals. So I encapsulated all the important parts in a demo app that combines the default project templates for Web API and Blazor.
See the full sample here:
https://github.com/jsauve/WebApiPlusBlazorWithAuth0JwtAndCookies