I am developing a Blazor Server application (.net 9) with Cosmos DB as database. I would like to add user auth with Entra External ID.
The only good docs I found are with Asp.Net MVC, here:
Does anyone have a github example app with Blazor? Or a link to tutorial?
I managed to make it work with the following steps.
Entra External ID Steps
Create an external tenant: https://learn.microsoft.com/en-us/entra/external-id/customers/how-to-create-external-tenant-portal
Prepare your external tenant: https://learn.microsoft.com/en-us/entra/external-id/customers/tutorial-web-app-dotnet-sign-in-prepare-tenant
Blazor Application Steps
Add package Microsoft.Identity.Web: https://www.nuget.org/packages/Microsoft.Identity.Web
Configure your Blazor application in appsettings.json: https://learn.microsoft.com/en-us/entra/external-id/customers/tutorial-web-app-dotnet-sign-in-prepare-app#configure-the-application-for-authentication
Add authentication and authorization to program.cs
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration)
.EnableTokenAcquisitionToCallDownstreamApi()
.AddInMemoryTokenCaches();
builder.Services.AddCascadingAuthenticationState();
...
app.UseAuthentication();
app.UseAuthorization();
Add authorization at the page level. Before the page is rendered, it will ask for the user be authenticated: https://learn.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-9.0&tabs=visual-studio#authorize-attribute
Add authorization at the component level. The page is rendered, but some components are only displayed to authenticated users: https://learn.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-9.0&tabs=visual-studio#authorizeview-component
Add authorization at the code level: https://learn.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-9.0&tabs=visual-studio#procedural-logic